I’ve been reading the Boost C++ documentation and trying to figure out how to generate a random real number between 0 and 1, using the uniform_01 part of the library. Does anyone have any suggestions?
Based on suggestions, I’m using this code, but it generates the same random value every time.
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;
}
Sorry if I wasn’t clear; this question isn’t solved, by my answer or any other. It’s still generating the same random value each time.
There are a few ‘gotcha’s in this code:
random01()function does not take a reference to the generator, but rather a copy of the generator. So if you call the function multiple times with the same generator – it will produce the same value over and over again!staticuniform_01inrandom01()only gets initialized on the first call to random01, so if it is ever called with a different generator, it will not use it, but rather use a reference to the first generator, which may even have been destroyed, since!Correct would be something like following (note the
&in the arguments list, for pass-by-reference, and the lack ofstatic: