[libcxx-commits] [PATCH] D115125: [libc++] Avoid rejection sampling in `uniform_int_distribution` if possible

Fabian Wolff via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Sun Dec 5 13:41:39 PST 2021


fwolff created this revision.
fwolff added reviewers: Quuxplusone, ldionne.
fwolff added a project: libc++.
fwolff requested review of this revision.
Herald added a subscriber: libcxx-commits.
Herald added a reviewer: libc++.

Fixes PR#39209 <https://bugs.llvm.org/show_bug.cgi?id=39209>. Suppose we have a URBG which generates values in the range [0, 12), and we want a uniform distribution for the range [0, 3). The current implementation will now use an independent bits engine to generate two independent bits using the URBG, i.e. the range [0, 4), and then do rejection sampling. But this is not necessary: Since URBG is supposed to generate uniformly distributed values, we can assume that each of the subranges [0, 3), [3, 6), [6, 9) and [9, 12) is equally probable, i.e. we can get a uniform value in [0, 3) by simply generating one value in [0, 12) and dividing it by 4 (=12/3).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115125

Files:
  libcxx/include/__random/uniform_int_distribution.h
  libcxx/test/std/numerics/rand/rand.dis/rand.dist.uni/rand.dist.uni.int/no_wasted_entropy.pass.cpp

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D115125.391939.patch
Type: text/x-patch
Size: 3236 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20211205/1d0e1d47/attachment.bin>


More information about the libcxx-commits mailing list