Re: random integer



On Tue, 24 Apr 2007 23:14:15 -0700, bob wrote:

I was just wondering what the best way to generate a uniformly
distributed random integer between 0 and x is.

Usually, you can't just do rand()%(x+1). For instance, if you want a
number between 0 and 31999, you can't just do rand()%32000 since
0-767 will be twice as likely.

In fact using mod to generate random integers within a range can be a
seriously bad idea anyway, since it utilises the low-order bits of the
random deviate and these are frequently not very random! This is
particularly true of linear congruential style prngs, which tends to
include many standard "system" rand() functions.

Better is to convert your (integer) random deviate to floating point,
divide it by RAND_MAX to get a random number between 0 and 1, then
multiply by x; something like (in C):

int rani(int x)
{
return (int)(((double)rand()/(double)RAND_MAX)*(double)x)
}

This should return a uniform random int in the range [0,x]

There will still be a problem if we don't have x << RAND_MAX. To extend
the "granularity" I guess you'd have to generate further rand()'s.

--
Lionel B
.