One common way of choosing a random number in [0, n) is to take the result of rand()
modulo n: rand() % n
. However, even if the results returned by the available rand()
implementation are fully uniform, shouldn't there be a problem with the uniformity of the resulting [0, n) numbers when RAND_MAX + 1
does not divide evenly by n? E.g. suppose RAND_MAX
is 2, and n is 2. Then out of 3 possible rand()
outputs: 0, 1 and 2, we get 0, 1 and 0 respectively when we use them modulo n. Therefore the output will not be uniform at all.
Is this a real problem in practice? What is a better way of choosing random numbers in [0, n) uniformly deriving from rand()
output, preferably without any floating point arithmetic?