One common way to select 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 completely homogeneous, there should be no problem with the uniformity of the obtained [0, n) numbers when RAND_MAX + 1 does not divide evenly by n? For example. Assume that RAND_MAX is 2 and n is 2. Then out of the 3 possible outputs of rand() : 0, 1 and 2 we get 0, 1 and 0, respectively, when we use them modulo n. Therefore, the output will not be uniform.
Is this a real problem in practice? What is the best way to select random numbers in [0, n) uniformly obtained from rand() output, preferably without any floating point arithmetic?
c random uniform
dragonroot Oct 27 2018-12-12T00: 00Z
source share