Re: random integer
- From: Richard Heathfield <rjh@xxxxxxxxxxxxxxx>
- Date: Wed, 25 Apr 2007 07:59:01 +0000
bob@xxxxxxxxxxxxxx said:
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.
Without getting seriously clever about it, you can do this:
int rir(int low, int high)
{
return (high - low + 1) * (rand() / (RAND_MAX + 1.0)) + low;
}
This won't give a perfectly uniform distribution, but it'll be a lot
better than a straight mod!
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
.
- References:
- random integer
- From: bob
- random integer
- Prev by Date: Re: random integer
- Next by Date: Re: random integer
- Previous by thread: Re: random integer
- Next by thread: Re: random integer
- Index(es):