rand1Random number generation in C - code walk-thru
Random number generation in C++ - code walk-thru
std::random_device
random_device::entropy() returns 0 if it’s deterministic/dev/urandom in Linuxrand2Generating normal-distributed random numbers
normal_distribution<> distro { 0.0, 3.5 };Mersenne Twister engine
mt19937: predefined specializations of the mersenne_twister_engine
class template
Mersenne Twister
(A little detour to the) Danger of narrowing conversion
Subtle bug without lround()
int x { distro(engine) }; // we get a compiler warning at least
int x = distro(engine); // we don't even get a warning here
Stateful functor
Binding engine to distro:
//int x = lround( distro(engine) );
auto generator = bind(distro, engine);
int x = lround( generator() );
We can fix it by moving the generator object outside the loop!
Alternatively, we can fix it by using std::ref():
auto generator = bind(distro, ref(engine));
std::ref() pseudocode overviewOr capture distro and engine in a lambda:
auto generator =
//[distro, engine] () { return distro(engine); }; // (1)
//[distro, engine] () mutable { return distro(engine); }; // (2)
//[=] () mutable { return distro(engine); }; // (3)
//[&distro, &engine] () { return distro(engine); }; // (4)
//[&] () { return distro(engine); }; // (5)
int x = lround( generator() );
rand3Very stateful functor
default_random_engine is linear_congruential_engine