RAND - obtain pseudo-random number.

(ANSI Standard)


#include <stdlib.h>
i = rand();


int i;
is a pseudo-random number in the range 0 to RAND_MAX (where RAND_MAX is a manifest defined in <stdlib.h>).


"rand" returns a pseudo-random number. Each new call to "rand" returns a new number.

This implementation uses a "linear congruential" generator. These generators are very fast, but have the property that the lowermost bits of the number returned may not be particularly random. The number returned is a "good random number" in the sense that:

rand()/((double)RAND_MAX + 1)

is a good approximation to a uniform random distribution in the interval 0<= r < 1. Thus if you want to generate a floating point number in the range [0,X) (including zero, but strictly less than X), you could use the formula:

X * (rand() / ((double)RAND_MAX + 1))

but the following would be a little better.

rand()/(((double)RAND_MAX + 1) / X)

Thus, if you want to generate a random sequence of integers between 0 and N-1, you could use the formula:

rand()/(int)(((unsigned)RAND_MAX + 1) / N)

However, truncation in the denominator means that this will sometimes produce N. You could produce a floating point number and truncate to an integer.

(int)(rand() / (((double)RAND_MAX + 1)/ N));

but it is better just to discard the occasional N that is generated, as in

while (N <= (val = rand() / (RAND_MAX/N)));

See Also:

expl c lib srand

Copyright © 1996, Thinkage Ltd.