PDA

View Full Version : C++ Random Double Generator

aaeyers
Apr 14, 2008, 01:06 PM
I'm trying to write a function that takes in two double values as high and low inclusive boundaries, and returns a random double in that range. I tried to just use the same function I wrote for integers, but of course the % operator does not play well with doubles. Does anyone know an easy way to write this kind of function for double values?

lee1210
Apr 14, 2008, 01:19 PM
get a random double between 0 and (max - min), then add min?

-Lee

aaeyers
Apr 14, 2008, 01:30 PM
Oh man I feel stupid now; I forgot about fmod(), problem solved.

double randomnumgen(double low, double high)
{
double range=(high-low);
double num = fmod(rand(),range)+low;
return(num);
}

lazydog
Apr 14, 2008, 04:57 PM
Oh man I feel stupid now; I forgot about fmod(), problem solved.

double randomnumgen(double low, double high)
{
double range=(high-low);
double num = fmod(rand(),range)+low;
return(num);
}

I'm not entirely sure that will work. For example if range=2.0 then you're only ever going to get either the values low or low+1 returned. Perhaps something like this would work better:-

double num = rand() * range / RAND_MAX + low ;

or if you're paranoid:-

double num = static_cast<double>( rand() ) * range / static_cast<double>( RAND_MAX ) + low ;

b e n