Welcome to Web-News
A Web-based News Reader
Subject Re: random number within a specified range?
From Don <nospam@nospam.com.au>
Date Thu, 09 Oct 2008 15:33:49 +0200
Newsgroups digitalmars.D.learn

Jarrett Billingsley wrote:
> On Sun, Oct 5, 2008 at 7:34 PM, Michael P. <baseball.mjp@gmail.com> wrote:
>> Hi,
>>
>> How would I go about getting a random number that was in a specified range of 2 numbers?
>> For example, getting a number inbetween 1000 and 2000.
>>
>> -Michael P.
>>
>
> lo + rand() % (hi - lo)
>
> assuming you're using Phobos, where rand() returns a number in the
> range [0, uint.max].
>
> This will get you a number in the range [1000, 2000); that is, it will
> be at least 1000 and at most 1999.  If you need 2000 to be one of the
> numbers generated, use 2001 as the hi.
The random numbers will not be evenly distributed, though. You'll get
more which are closer to 1000 than to 2000.

(Imagine uint.max = 1000. Then 0 and 1000 map to 1000, but every other
number has only one number which maps to it).

Simple way to fix this is to ignore numbers from the non-uniform part:

uint rmax = uint.max - (uint.max % (hi-lo));
uint r;
do {
   r = rand();
} while (r>rmax);
return lo + r % (hi - lo);

Recent messages in this thread
 
-# random number within a specified range? Michael P. 05-Oct-2008 07:34 pm
.-# Re: random number within a specified range? Jarrett Billingsley 05-Oct-2008 07:37 pm
..\# Re: random number within a specified range? (Current message) Don 09-Oct-2008 09:33 am