How many random numbers does std :: uniform_real_distribution use?

I was surprised to see that the output of this program:

#include <iostream> #include <random> int main() { std::mt19937 rng1; std::mt19937 rng2; std::uniform_real_distribution<double> dist; double random = dist(rng1); rng2.discard(2); std::cout << (rng1() - rng2()) << "\n"; return 0; } 

is 0 - that is, std::uniform_real_distribution uses two random numbers to create a random double value in the range [0,1]. I thought it would just generate one and rescale it. Thinking about this, I assume that this is due to the fact that std::mt19937 creates 32-bit int and double twice this size and, therefore, is not "random enough".

Question: How to find out this number in the general case, i.e. if random number generator and floating point type are arbitrary types?

Edit: I just noticed that instead of std::generate_canonical I could use, since I am only interested in random numbers [0,1]. Not sure if that matters.

+6
source share
1 answer

For template<class RealType, size_t bits, class URNG> std::generate_canonical standard (section 27.5.7.2) explicitly defines the number of calls for a uniform random number generator (URNG) as

max (1, b / log_2 R),

where b is the minimum number of bits in the RealType mantissa and the number of bits set for generate_canonical as a template parameter. R is the range of numbers that URNG can return (URNG::max()-URNG::min()+1) . However, in your example, this will not make any difference, since you need 2 calls to mt19937 to fill 53 bits of the double mantissa.

In other distributions, the standard does not provide a general way to get any information about how many numbers a URNG should generate in order to get one distribution number.

The reason may be that for some distributions the number of uniform random numbers needed to create one distribution number is not fixed and can vary from call to call. An example is std::poisson_distribution , which is usually implemented as a loop that draws a uniform random number at each iteration until the product of these numbers reaches a certain threshold (see, for example, the GNU C ++ library implementation (line 1523- 1528)).

+2
source

Source: https://habr.com/ru/post/949982/


All Articles