I’m trying to generate a random real number between 0 and 1, using the Boost C++ uniform_01 functions and the Mersenne Twister algorithm. This is my code:
double random01(mt19937 & generator)
{
uniform_01<mt19937> dist(generator);
return dist();
}
int main()
{
mt19937 generator(time(0));
for (int i = 0; i < 10; i++) {
cout << random01(generator) << endl;
}
return 0;
}
However, this code generates the same random number on every iteration of the loop. I know this is a repeat of this question, but that question was closed for being ambiguous, so I rephrased it.
That’s not quite how you use a distribution. More like this:
As you can see, the distribution object is independent of everything else, so in fact you might like to make it a global, or perhaps a static variable.
(Note that
uniform_01didn’t make it into the final standard, but insteaduniform_real_distribution‘s default constructor defaults to the interval [0, 1]. For the old Boost class you can use the analogous approach.)