Random Number Generator Cofirmation

129 views Asked by At

I just wanted to know if the following code actually include the value 3.0? (I know rand() is not the best, but I just wanted to try this out)

//function returns random double value between specificed range, inclusively.
double randomDouble (double minVal, double maxVal) {
    return double(rand()) / RAND_MAX * (maxVal - minVal) + minVal;
}

My logic was that

  1. double(rand()) / RAND_MAX gives random numbers in range 0.0 to 1.0, inclusive
  2. (maxVal - minVal) then turns that into 0.0 to MaxVal, inclusive
  3. adding minVal finally gives us random double values from minVal to maxVal, inclusive.

So, I tried to test if they really include maxVal by running this code:

int cnt = 0;
for (int i = 0; i < 999999999; i++) {
    if (randomDouble(1.0, 3.0) == 3.0) {
        cnt++;
    }
}
cout << cnt << endl;

But the cnt was zero always.

So I wasn't sure if my function was right?

1

There are 1 answers

3
Mark Ransom On

The only way your function could return maxVal is when rand() returns exactly RAND_MAX. That's going to be exceedingly rare, testing 999999999 times may not be enough to hit it.