As a followup to my previous post on generating random numbers, Jon Kean pointed me to Shinobu’s post on generating random numbers without modulo bias:
Let’s say you need a random number from 0 to 2 (0, 1 or 2). If you do this:
int x;
int n = 3;
x = rand() % n;
return x;your code is broken, thanks to modulo bias. You will always get modulo bias whenever RAND_MAX + 1 of your rand() function is not evenly divisible by your modulus n.
Shinobu goes on to explain the details and offers an alternative approach.