Re: random integer



On Apr 25, 3: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.

As other posters mention, rejection solves this. Take enough bits from
your binary RNG and reject outcomes that are outside your range. Each
remaining outcome is equally probable (depending on the quality of
your RNG, of course). For example, if you want 0..999, take 10 bits
and reject 1000..1023.

Sample code at https://www.telegraphics.com.au/svn/rejection/trunk/

.