NL3
NL3

Reputation: 127

C++ random numbers are always the same

I am currently stuck at generating random numbers during runtime. In Java, I just call Math.random() and I'm pretty much done (I just need a simple RNG). In C++, I have tried several ways to generate random numbers and always end up getting the same.

Currently, I am using the following method to get a random number between MIN and MAX:

unsigned int getRandomNumber(int min, int max){
    std::mt19937 mt(1729);
    std::uniform_int_distribution<int> dist(min, max);
    return dist(mt);
}

I have an object that calls this function in its constructor and assigns the value returned to an attribute. I currently create five instances of this object and the random number is always the same. Setting a big range (1 - 1000) does not change this. The number is always the same. Security is not a concern, it is an extremely simple application.

Upvotes: 1

Views: 2294

Answers (2)

Hatted Rooster
Hatted Rooster

Reputation: 36463

A random number generator works with a seed. Basically it's a number that's set only once for the random number generator to work with. If you re-seed your random number generator each time you try to generate an number you will get the same number every time. You should create the std::mt19937 object only once.

Upvotes: 7

Jfevold
Jfevold

Reputation: 422

unsigned int getRandomNumber(int min, int max){
    static std::mt19937 mt(1729);
    std::uniform_int_distribution<int> dist(min, max);
    return dist(mt);
}

Making mt static will cause it to only be instantiated once, which means it will only be constructed once, which means it will only be seeded once. Even with this fix, you'll still get the same series of numbers each time you run the program, but they'll be different each time you call getRandomNumber in one single execution.

A much better solution would be to instantiate the mt variable elsewhere, and pass it in to this function as a parameter, that way you could manage how it is seeded with more code than just a constructor call. Typically you would seed with a value based on time. Lots of insight here.

Upvotes: 2

Related Questions