crandomglibcansi-clcg

What is the modulus of the glibc pRNG LCG?


I'm a bit confused at the moment about the linear congruential generator used in the rand() function in stdlib to generate random numbers. The table on https://en.wikipedia.org/wiki/Linear_congruential_generator lists the modulus used by GCC and for ANSI C as 2^31. However, according to https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf p347, for ANSI C 2^32 is implicitly used. Does rand() in stdlib also use 2^32?

I've implemented and tested the ANSI C implementation, which works fine.


Solution

  • In Glibc, rand (defined in rand.c). is a just a wrapper for __random. And __random (defined in random.c is just a wrapper for __random_r. And __random_r (defined in random_r.c) has two different code paths, but I think the relevant one is this one:

         int32_t val = ((state[0] * 1103515245U) + 12345U) & 0x7fffffff;
         state[0] = val;
         *result = val;