std::mt19937 doesn't return random number

14,454

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() << " ";   
}
Share:
14,454
marc3l
Author by

marc3l

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” - Martin Fowler 0110110101100001011100100110001101100101011011000110100001101111011001010110110001101100001011100110010001100101

Updated on June 28, 2022

Comments

  • marc3l
    marc3l almost 2 years

    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?