2
//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!!

AbhiJoe
  • 23
  • 7

2 Answers2

2

From std::random_device :

std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.

Although it's not ideal for it's users, an implementation is allowed to have the behavior you described.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
1

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402