Re: random integer



On Apr 25, 2:14 am, b...@xxxxxxxxxxxxxx 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.

You can throw away the "extra" random values. Pick the largest N s.t.
N * (x+1) - 1 is produced by RNG. Then

while ((n = rand()) >= N * (x+1))
/* skip */ ;
return n % (x + 1);

But note that standard rand() is a very bad random number generator.


.