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

*From*: Ertugrul Söylemez <es@xxxxxxxx>*Date*: Tue, 11 Aug 2009 08:13:25 +0200

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.

.

**Follow-Ups**:**Re: Efficient way to gen a random number in a particular range?***From:*Ilmari Karonen

**References**:**Efficient way to gen a random number in a particular range?***From:*Dave -Turner

**Re: Efficient way to gen a random number in a particular range?***From:*Scott Contini

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

- Prev by Date:
**Re: Efficient way to gen a random number in a particular range?** - Next by Date:
**Re: Efficient way to gen a random number in a particular range?** - Previous by thread:
**Re: Efficient way to gen a random number in a particular range?** - Next by thread:
**Re: Efficient way to gen a random number in a particular range?** - Index(es):