You should not use the mod %
operator to narrow the random range, because the probability of the numbers will not be the same· For example, if RAND_MAX
is 256, the number 1 would have a higher probability than the rest.
You can test this in Python, there is roughly twice the number of zeros than ones:
>>> sorted([(random.randint(0, 2) % 2) for x in range(100)])
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
To get the same probability distrubution as the Java cone from C you should do something like:
/* Returns a random number from 0 to limit inclusive */
int rand_int(int limit) {
return ((long long)limit * rand()) / RAND_MAX
}