Help on C++0x random generator

I had the following code:

#include <random>
#include <functional>
#include <ctime>

double GetRN(double min = 0.0, double max = 1.0)
{
// using C++0x new feature of uniform_real_distribution, mt19937

std::uniform_real_distribution<double> distribution(min, max);
std::mt19937 engine(time(NULL));
std::function<double()> urand = std::bind(distribution, engine);
return urand();

}

Then to run in the main() with:
for(int i = 0; 10 != i; ++i) std::cout << "GetRN : " << GetRN() << std::endl;

The result is always with 10 of the same number, such as:
GetRN : 0.792169
GetRN : 0.792169
...

But I would like to have different random number for each call of GetRN(). Is there any particular point that I missed in the function GetRN()?

You create the RNG with the same seed each time you call the function so that is why you always get the same number. To get different numbers you should reuse the same RNG to generate all the random numbers.
A simple way to achieve what Peter87 pointed out is to use a function-local static and drop the function:

1
2
3
4
5
6
double GetRN(double min = 0.0, double max = 1.0)
{
    std::uniform_real_distribution<double> distribution(min, max);
    static std::mt19937 engine(time(NULL));
    return distribution(engine);
}
@Cubbi, your solution really helps!To make the variable "engine" static is to make sure even when the method GetRN() ends, the variable "engine" remains its value. So the next time when GetRN() is called, the value of "engine" is still the same? I think I am quite lost on the logic behind your solution, can you kindly give me more information? Thanks thanks!

@Peter87, thanks for your clarification! I tried to put this method into a class URandom. When I generate different objects of URandom and then call this method from these objects, they still give me the same number. So, using this RNG method via different objects is actually NOT reusing the RNG to generate random numbers?



Topic archived. No new replies allowed.