Contributors: 1 Thursday, October 6, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap

Restrict generation to a given range


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.

The macro

#define uniform() (rand() / (RAND_MAX + 1.0))

produces a p value on 0.0 to 1.0 - epsilon, so

i = (int)(uniform() * N)

will set 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.