I'm using srandom() and random() to generate random numbers in c on a Unix system. I would like to have multiple RNGs. Each one, given the same seed, should output the same sequence. I would also like to save and restore the state of each one. Here's a pseudocode example:
R1 = new_rng(5); //5 is the seed
R2 = new rng(5); //5 is the seed here, too.
a = R1.random();
b = R1.random();
d = R2.random(); //a == d
s1 = R2.get_state(); //save the state of R2
e = R2.random(); //b == e
R2.set_state(s1); //restore the state of R2
f = R2.random(); //b == f
How do I do this? Sometimes the RNGs will fork into different threads and I need to replicate the state of the RNG when creating a new thread, too.
Use erand48()
/nrand48()
/jrand48()
to generate double precision floating point, non-negative long integer, or signed long integer random numbers, respectively. These functions allow you to have as many independent sequences as desired; the state is passed in as an argument and can easily be saved and restored. Furthermore, the sequence is defined by the standard and will not vary across runs, even on different platforms.
Some other answers suggest rand_r()
. This function is obsolescent in POSIX.1-2008, which contains this note:
The
drand48()
function provides a much more elaborate random number generator.The limitations on the amount of state that can be carried between one function call and another mean the
rand_r()
function can never be implemented in a way which satisfies all of the requirements on a pseudo-random number generator. Therefore this function should be avoided whenever non-trivial requirements (including safety) have to be fulfilled.The
rand_r()
function may be removed in a future version.