Restrict generation to a given rangesuggest change
Usually when generating random numbers it is useful to generate integers within a range, or a p value between 0.0 and 1.0. Whilst modulus operation can be used to reduce the seed to a low integer this uses the low bits, which often go through a short cycle, resulting in a slight skewing of distribution if N is large in proportion to RAND_MAX.
#define uniform() (rand() / (RAND_MAX + 1.0))
produces a p value on 0.0 to 1.0 - epsilon, so
i = (int)(uniform() * N)
i to a uniform random number within the range 0 to N - 1.
Unfortunately there is a technical flaw, in that RAND_MAX is permitted to be larger than a variable of type
double can accurately represent. This means that
RAND_MAX + 1.0 evaluates to RAND_MAX and the function occasionally returns unity. This is unlikely however.
Found a mistake? Have a question or improvement idea? Let me know.
Table Of Contents