Thread overview
random number within a specified range?
Oct 05, 2008
Michael P.
Oct 09, 2008
Don
October 05, 2008
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.
October 05, 2008
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.
October 09, 2008
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);