Home > DeveloperSection > Forums > Generate Random numbers uniformly over entire range
Tanuj Kumar

Total Post:134

Points:940
Posted on    May-07-2013 12:55 AM

 Visual C++ Visual C++ 
Ratings:


 1 Reply(s)
 776  View(s)
Rate this:
Hi All!

I need to generate random numbers with in specified interval [max,min]

Also the random numbers should be uniformly distributed over interval, not located to particular point

Currenly I am generating as:

for(int i=0;i<6;i++)
{
DWORD random= rand()%(max-min+1) + min;
}
From my tests random numbers are generated around one point only

Example
min= 3604607;
max= 7654607;
Random numbers generated:

3631594
3609293
3630000
3628441
3636376
3621404
Edit (added from answers below): Ok RAND_MAX is 32767. I am on C++ windows platform.. Is there any other method to generate random numbers with uniform distribution?

Thanks in advance! 



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-07-2013 7:50 AM

Hi Tanuj!

Generally, the high bits show a better distribution than the low bits, so the recommended way to generate random numbers of a range for simple purposes is:

((double) rand() / (RAND_MAX+1)) * (max-min+1) + min
Note: make sure RAND_MAX+1 does not overflow! (Thanks Demi)

the division generates a random number from the interval [0, 1), "stretch" this to the required range. Only when max-min+1 gets close to RAND_MAX you need a "BigRand()" function like posted by Mark Ransom.

This also avoids some slicing problems due to the modulo, which can worsen your numbers even more.

Don't want to miss updates? Please click the below button!

Follow MindStick