Mail Archives: djgpp/1997/03/07/16:03:41
John M. Aldrich <fighteer AT cs DOT com> wrote:
>
>To get a random number from 0 to X - 1, use:
>
> n = random( ) % X;
>
>Before everybody gets hysterical on me again, let me say in advance that
>the GNU random() RNG, unlike rand(), is guaranteed to be random in the
>lower bits, so you can use the mod operator safely.
The numbers will still not be uniformly distributed. Smaller values are
more likely than large ones. To understand why, remember that random()
and rand() return an integer between 0 and RAND_MAX. Suppose, just for
the sake of argument, that RAND_MAX == 5 and you want random numbers
from 0 to 3. Then random()%4 will evaluate to 1 when random() returns
*either* 1 or 5, but the only way to get a 3 is for random() to return
exactly 3. In other words 0 and 1 are twice as likely to occur as 2 and
3 in this case. Even with a large RAND_MAX (like 2^31), the numbers at
the small end of (0,X) will be more likely than those at the high end.
The best way to get get random numbers uniformly distributed from
0 to X-1 is to use:
n = ((double)random() / RAND_MAX) * X;
If you want to cast n to an int, that's your business.
-- Dave Cigna
- Raw text -