Re: Efficient way to gen a random number in a particular range?



MTGAP schrieb:
I assume Scott is doing this because modding by a power of 2 can be
efficiently implemented with the bitwise AND operation. But it's
faster (and simpler) to do it like this:

x = prng() % 40 + 10;

Bad method, because it's biased towards 0..15. Mod 41 is also bad,
because it's biased towards 0..36. Modulo operation is only good in
this case, if your module is a power of 2. In all other cases you
should use 64 bit integer operations and do it this way:

r <- prng
40*r / 2^32

This yields a number 0..39. Generally replacing 40 by n yields a number
0..n-1.


Greets,
Ertugrul.
.