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



On Aug 11, 2:49 pm, MTGAP <mtga...@xxxxxxxxx> wrote:
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

Not exactly.
Assume that the prng() outputs 32-bit values
uniformly. The goal is to make the modified
prng that outputs values uniformly in the desired
range. I claim that the code I posted does that,
and the code you posted does not.


faster (and simpler) to do it like this:

x = prng() % 40 + 10;


I think he wanted the range to be inclusive
of 10 and 50, which means you should mod by 41.

Scott

.