33
votes

Is there any way to achieve same random int numbers sequence in different operating system with same seed? I have tried this code:

std::default_random_engine engine(seed);
std::uniform_int_distribution<int> dist(0, N-1);

If I ran this code on one machine multiple times with same seed, sequence of dist(engine) is the same, but on different operating system sequence is different.

1
Because std::default_random_engine doesn't have to be the same PNRG on each system, use std::mt19937.Hatted Rooster
I believe a particular random engine like std::mt19937 is required to give the same numbers for a particular seed but I don't think the distribution is. So you might have to write your own distribution.Chris Drew
Even if you use std::mt19937 for the seed, the distributions like std::discrete_distribution yield different results.anilbey

1 Answers

40
votes

Yes there is, but you need a different or to put it exactly, the same PRNG on each platform. std::default_random_engine engine is a implementation defined PRNG. That means you may not get the same PRNG on every platform. If you do not have the same one then your chances of getting the same sequence is pretty low.

What you need is something like std::mt19937 which is required to give the same output for the same seed. In fact all of the defined generators in <random> besides std::default_random_engine engine will produce the same output when using the same seed.

The other thing you need to know is that std::uniform_int_distribution is also implementation defined. The formula it has to use is defined but the way it achieves that is left up to the implementor. That means you may not get the exact same output. If you need portability you will need to roll you own distribution or get a third party one that will always be the same regardless of platform.