Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Achieve same random number sequence on different OS with same seed

Tags:

c++

random

c++11

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.

like image 426
tty6 Avatar asked Nov 01 '16 13:11

tty6


People also ask

Can you generate the same random numbers everytime?

random seed() example to generate the same random number every time. If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function. Let's see how to set seed in Python pseudo-random number generator.

What happens when specify a seed value for a random number generator?

The seed() method is used to initialize the random number generator. The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time.

Which function is used to seed a new random number sequence?

Answer: The srand function seeds the pseudo-random number generator (PRNG) used by the rand () function. It is a standard practice to use the result of a call to time (0) as seed.


1 Answers

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.

like image 133
NathanOliver Avatar answered Sep 20 '22 23:09

NathanOliver