rand()

#include <stdlib.h>

int rand( void );

This function returns a pseudorandom integer in the range 0 to RAND_MAX (a macro defined in stdlib.h.

See also: srand().


Back to Essential C Functions.

ANSI C
The ANSI C PRNG is a linear congruential PRNG which returns an integer in the range 0 to RAND_MAX-1 inclusive, where RAND_MAX is at least 32767. One complaint PRNG is of the form:

Xn = (1103515245 * Xn-1 + 12345) mod RAND_MAX

Assume that when you seed this, the seed = X0

Microsoft C
This is the PRNG in the MS C library version 4.0. It returns an integer in the range 0 to 32767 inclusive.

TEMP = (214013 * Xn-1 + 2531011) mod 2147483648
Xn = INT(TEMP / 65536)

Note than neither ANSI nor POSIX require that a specific algorithm be used by rand(). Generally the only restriction on it is that, within a single process, rand() will always return the same sequence of numbers after it is seeded with srand() using the same seed.

For example, the GNU C library, glibc uses (to quote the man page), "a non-linear additive feedback" generator, which is very unlike the linear congruential PRNGs used by many other C libraries. The primary reason for this is that, while a LCRNG is easy to code, the lower-order bits are often very unevenly distributed. In fact, you will note in DrT's writeup in this same node, Microsoft's LCRNG shifts the intermediate result over by 16 bits, giving better bit distributions in the lower part of the return value.

You can't even assume that the return values of rand() will stay the same from one run of your program to the next, because in the presence of shared libraries, it's entirely possible that someone could upgrade the library, and it will have changed the RNG algorithm used.

It's a common mistake to assume that the return values of rand() are portable. The function, itself, is a useful and portable tool, but don't try to give it semantics that it does not have, and are not defined by any standard.

Take a look at this nice short C program:


#include <stdio.h>
#include <stdlib.h>

int main()
   {
   srand(5);
   printf("%d\n", rand());
   return 0;
   }

The result of running this on a sampling of systems:

Linux (glibc 2.2): 590011675

Solaris 2.6 and IRIX 6.5: 18655

MacOS X: 1222621274

Log in or register to write something here or to contact authors.