6
double get_random(double min, double max) {
  /* Returns a random double between min and max */

  return min * ((double) rand() / (double) RAND_MAX) - max;
}

That's my function to generate random doubles between a min and a max. However, when I call get_random(-1.0, 1.0);, I get values between -2.0 and -1.0.

Any idea of what I'm doing wrong and how I can fix it?

jogojapan
  • 68,383
  • 11
  • 101
  • 131
David Gomes
  • 5,644
  • 16
  • 60
  • 103

2 Answers2

21

Shouldn't the formula be

(max - min) * ( (double)rand() / (double)RAND_MAX ) + min
  • (double)rand() / (double)RAND_MAX returns a random number between 0 and 1
  • (max - min) * ( (double)rand() / (double)RAND_MAX ) returns a random number between 0 and max - min.
  • the whole expression will return a random number between 0 + min and min + (max-min) - i.e. min and max.
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 2
    Just as a warning: this method will probably generate a small fraction, well under 1%, of possible random numbers in your selected range. Use `` (if available) for higher-quality random doubles. – Robert Cooper May 27 '12 at 19:13
1

You can use this for generating random double or floating numbers:

((double) rand()*(max-min)/(double)RAND_MAX-min);
jogojapan
  • 68,383
  • 11
  • 101
  • 131
  • Is there any specific advantage of this compared to the accepted answer? Could you explain more? – jogojapan Jun 24 '13 at 03:20
  • 2
    I agree with @jogojapan, and the final `-min` is the only difference from the accepted answer of `+min` (as far as I can see), thus this answer is wrong. – Ken Y-N Jun 24 '13 at 03:27