Multiple random number generator states in c/Unix Multiple random number generator states in c/Unix unix unix

Multiple random number generator states in c/Unix


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.


Read this article on Mersenne twister. There are links to several implementations at the very bottom. (In other words, implement a PRNG yourself.)


there are some C library extension on various UNIX flavours:

  • BSD like random, check initstate/setstate
  • _r variants (random_r, srandom_r, initstate_r, etc)
  • rand_r (stdlib.h)

which flavour is supported by your target UNIX?