c++randomnumbersmt19937

C++ 11 random number generation not working


//My trial program
#include<iostream>
#include<random>

using namespace std;

int main(){

    //USed to initialize (seed) the random number generator
    random_device sd{};

    // The random number generator
    mt19937 engine {sd()};

    //Uniformly distribute random numbers in [1...10]
    uniform_int_distribution <> dis{1, 50};

    //Generate a random integer
    int x {dis(engine)};

    //Print it 

    cout<<x<<"\n";

    return 0;

}

I have used the code above to a generate random number between 1 to 50. But whenever I run the program, the random number generated is the same. An online course that I am taking has this code and it works perfectly fine on the instructor's clang compiler. I am using gcc compiler. Can anyone tell me what needs to be done please? thank you!!


Solution

  • The issue here is that std::random_device does not have to really be a random device. It can be a wrapper around an unseeded rand which would give you the same value every time you use it. This means your seed for engine would be the same which means the pseudo-random sequence it generates would be the same as well.

    One way you could get around this is to use the current as a seed like

    auto seed = std::chrono::system_clock::now().time_since_epoch().count();
    mt19937 engine {seed};
    

    But this can be manipulated via external processes and isn't very fined grained so multiple instances seeded at the same time could all make the same sequence.