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



On Aug 10, 10:21 pm, Scott Contini <the_great_cont...@xxxxxxxxx>
wrote:
do {
 x = prng() % 64;
while (x >= 41);
/* now x is between 0 and 40 */
output x + 10;

Scott

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;

There's a better way to do it, but it's harder to implement. You can
set up a linear congruential generator with a cycle from 0 to 40 and
then add 10.

function prng() {
x = (21 * x + 19) % 40;
}
This is a linear congruential generator that generates random numbers
from 0 to 40 with the maximum possible period.

Then do:
x = prng() + 10;

This is marginally more efficient than the other method. It's probably
not worth it to implement this since the improvement is slight. You
should not use it if you want a period greater than 40.
.