Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

aaeyers

macrumors newbie
Original poster
Feb 16, 2008
27
0
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?
 

aaeyers

macrumors newbie
Original poster
Feb 16, 2008
27
0
Oh man I feel stupid now; I forgot about fmod(), problem solved.

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

lazydog

macrumors 6502a
Sep 3, 2005
709
6
Cramlington, UK
Oh man I feel stupid now; I forgot about fmod(), problem solved.

Code:
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:-

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

or if you're paranoid:-

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



b e n
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.