Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the modulus of the libc 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading