C++ Random Double Generator

Discussion in 'Mac Programming' started by aaeyers, Apr 14, 2008.

  1. macrumors newbie

    Joined:
    Feb 16, 2008
    #1
    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?
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    get a random double between 0 and (max - min), then add min?

    -Lee
     
  3. thread starter macrumors newbie

    Joined:
    Feb 16, 2008
    #3
    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);
    }
     
  4. macrumors 6502a

    Joined:
    Sep 3, 2005
    Location:
    Cramlington, UK
    #4
    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
     

Share This Page