Re: random integer
- From: Gene <gene.ressler@xxxxxxxxx>
- Date: 27 Apr 2007 16:14:55 -0700
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.
.
- References:
- random integer
- From: bob
- random integer
- Prev by Date: Re: How to judge if the graph is cyclic when add a new edge?
- Next by Date: Applications that use thousands of data containers?
- Previous by thread: Re: random integer
- Next by thread: Re: random integer
- Index(es):