Home c++ Random number generator std :: mt19937 from & lt; random & gt;...

Random number generator std :: mt19937 from & lt; random & gt; always returns the same number

Author

Date

Category

Hello. I need to create a function that would return a random number. Below you can see how I tried to implement it. There are no errors, the number is there, the problem is that the number is always the same. Well, as you probably already guessed, the question is, how can I fix this situation? Preferably with an example.

int TestClass :: returnRandom (int max) {
std :: random_device randD;
std :: mt19937 randMT (randD ());
std :: uniform_int_distribution & lt; int & gt; range (0, max);
return range (randMT);
}

Answer 1, authority 100%

The problem is that randMT is recreated every time.

std :: mt19937 is a pseudo-random number generator, to get a sequence of numbers it must be created once, and then used together with some random distribution to get random numbers.

Therefore, it must be made a member of the class:

class TestClass {
public:
 TestClass () {
  std :: random_device device;
  random_generator_.seed (device ());
 }
 int returnRandom (int max) {
  std :: uniform_int_distribution & lt; int & gt; range (0, max);
  return range (random_generator_);
 }
private:
 std :: mt19937 random_generator_;
};

If the class is created many times and often, then it makes sense to create the std :: random_device object not in the constructor, but somewhere else, since creating it can be a slow operation too.

The std :: mt19937 object can also be initialized with the current time. However, this is a weak source of entropy because the current time has very few random bits.

auto now = std :: chrono :: high_resolution_clock :: now ();
random_generator_.seed (now.time_since_epoch (). count ());

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions