The
rand () function generates a pseudo-random number in the range
[0, RAND_MAX]. You can initialize it with
srand (seed). In most cases, however, we want random numbers in a much smaller range
[0, M). What's the best way to do this?
Points to note:
- Most implementations of
rand () are linear-congruential generators. They generate a pre-defined sequence from the given seed that exhibits some "randomness".
-
rand (), therefore, should not be used when we require "serious" randomness (say for cryptographic applications).
-
rand () also should not be used when we depend upon large set of random numbers. As a rule of thumb you can generate 1/10 of RAND_MAX before the series stops exhibiting random behaviour.
When we need to adjust the range from
[0, RAND_MAX] to
[0, M) | (M<RAND_MAX) we should not use:
num = rand () % M;
as the result will focus on the lower bits of the
rand () result, which are much less random than the higher bytes (for a linear congruential generator).
The recommended way to get a random number in the required range is:
num = (int)(( ((double)rand ()) / ((double)(RAND_MAX) + 1.0) ) * M);
Points to note:
- We should not use the simpler:
(rand () * M)/(RAND_MAX + 1) as either (or both) of (rand () * M) and (RAND_MAX + 1) could overflow.
- 1.0 is a literal
double, hence no cast is required.