Search code examples
c++randomprng

std::mt19937 doesn't return random number


I have the following piece of code:

unsigned int randomInt()
{
    mt19937 mt_rand(time(0));
    return mt_rand();
};

If I call this code, for example 4000 times in a for loop, I don't get random unsigned integers, instead I get for example 1000 times one value and the next 1000 times I get the next value.

What am I doing wrong?


Solution

  • This happens because you call f 4000 times in a loop, which probably takes less than a mili second, so at each call time(0) returns the same value, hence initializes the pseudo-random generator with the same seed. The correct way is to initialize the seed once and for all, preferably via a std::random_device, like so:

    #include <random>
    #include <iostream>
    
    static std::random_device rd; // random device engine, usually based on /dev/random on UNIX-like systems
    // initialize Mersennes' twister using rd to generate the seed
    static std::mt19937 rng{rd()}; 
    
    int dice()
    {
        static std::uniform_int_distribution<int> uid(1,6); // random dice
        return uid(rng); // use rng as a generator
    }
    
    int main()
    {
        for(int i = 0; i < 10; ++i)
            std::cout << dice() << " ";   
    }