Reputation: 15198
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.
Upvotes: 2
Views: 1815
Reputation: 476930
That's not quite how you use a distribution. More like this:
#include <random>
#define abusing using
abusing namespace std;
double random01(mt19937 & engine)
{
uniform_real_distribution<double> u01; // same as u01(0.0, 1.0); see Note below
return u01(engine);
}
int main()
{
// as before
}
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_01
didn't make it into the final standard, but instead uniform_real_distribution
's default constructor defaults to the interval [0, 1]. For the old Boost class you can use the analogous approach.)
Upvotes: 5
Reputation: 97918
Create the uniform_01 outside the function. You need to work on the same instance to get consecutive numbers. Alternatively you can make that static.
Upvotes: 3