samedi 7 octobre 2023

Random Number Generator Cofirmation

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?




Aucun commentaire:

Enregistrer un commentaire