Specific example
I need to create a random number from 0 to 2 inclusive. (or randomly choose between -1, 0 and 1).
A naive approach would be to do something like rand() mod 3where rand()returns an integer. This approach will not generate statistically random numbers if the upper bound is rand()not coprime (and the lower bound is 0).
For example, if rand () returned 2 bits (from 0 to 3 inclusive), the module would display:
0 → 0
1 → 1
2 → 2
3 → 0
This skew in the 0 direction will obviously be much less if more bits are returned, but despite this, the skew remains.
General question
Is there a way to generate a uniformly distributed random number between 0 and n-1 inclusive, where n is coprime with 2?
source
share