Several states of the random number generator in c / Unix

I use srandom () and random () to generate random numbers in c on a Unix system. I would like to have some RNG. Each of them, given the same seed, should output the same sequence. I would also like to maintain and restore the condition of each of them. Here is an example of pseudo code:

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 can I do it? Sometimes RNGs will evolve into different threads, and I also need to replicate the state of the RNG when creating a new thread.

+3
source share
5 answers

erand48()/nrand48()/jrand48() , , . ; . , , .

rand_r(). POSIX.1-2008, :

drand48() .

, , , rand_r() , . , ( ).

rand_r() .

+6

Mersenne twister. . ( , PRNG.)

+1

C UNIX:

  • BSD , initstate/setstate
  • _r (random_r, srandom_r, initstate_r ..)
  • rand_r (stdlib.h)

UNIX?

+1

rand_r(unsigned *seed) srand() rand(). , .

+1

, PRNG, โ€‹โ€‹ , . , , , , . libc โ€‹โ€‹ , -. , ( , ).

In any case, this will very much connect your application with the PRNG implementation in your libc. You will definitely be associated with the flavor of libc that you are developing, and possibly even with the version of libc. If this feature is very important, you may need to redefine the random number in the application to ensure portability and reproducibility.

0
source

Source: https://habr.com/ru/post/1711572/


All Articles