Mt19937 and uniform_real_distribution

I am trying to find an efficient way to implement a uniform distribution (0,1). Since I have to generate a very large number of samples, I chose mt19937 as the engine. I am using the version from the boost library. My question is: what is the difference between using the engine of the engine itself versus using uniform_real_distribution?

Option number 1

std::random_device rd; boost::mt19937 gen(rd()); boost::random::uniform_real_distribution<double> urand(0, 1); for ( int i = 0; i < 1E8; i++ ) { u = urand(gen); } 

Option number 2

 std::random_device rd; boost::mt19937 gen(rd()); for ( int i = 0; i < 1E8; i++ ) { u = (double) gen()/gen.max(); } 

Of my tests, Option # 2 is significantly better than Option # 1 in terms of runtime. Is there any reason why I should choose option # 1 over Option # 2?

+5
source share
2 answers

I do not know the basic implementation of urand() , but using the result of division is likely to result in a bias in the lower bits as a quantization effect. If gen.max() is small, then the least significant bits can be very many or most bits of the result.

A performance mismatch may result from the creation of properly distributed random numbers. If double is too accurate for your needs, perhaps using a float may allow it to work more efficiently.

+1
source

My question is: what is the difference between using the engine itself versus using uniform_real_distribution?

In your first variant, urand() has a range of [0,1) , while the second option has a range of [0,1] (if boost::mt19937::min() == 0 , which is usually executed).

0
source

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


All Articles