Restrict generation to a given range
suggest changeWhen generating random numbers it is often useful to produce integers in a range, or a value p between 0.0 and 1.0. The remainder operation can reduce a rand result to a low integer, but that uses the low bits. Those bits often have a short cycle, which slightly skews the distribution when N is large relative to RAND_MAX.
The macro
#define uniform() (rand() / (RAND_MAX + 1.0))
produces a value on the half-open interval from 0.0 up to, but not including, 1.0, so
i = (int)(uniform() * N)
will set i to a uniform random number within the range 0 to N - 1.
RAND_MAX is not always exactly representable as a double. When it is not, RAND_MAX + 1.0 can round back to RAND_MAX, and the quotient can be 1.0. That is uncommon, but the result is then outside the intended range.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents