samedi 7 janvier 2017

Why divide 1.0/0x7FFFFFFFFFFFFFFF in this C example?

I am reading Game AI Pro 1, and in Chapter 3 on "Advanced Randomness..." I ran across a line of code I don't understand. The code is a Gaussian(ish) pseudorandom number generator returning values from -3.0 to 3.0 inclusive. The comment at the end is about the percentages of numbers falling within the 1st, 2nd, and 3rd standard deviations:

unsigned long seed = 61829450;
double GaussianRand()
{
    double sum = 0;
    for (int i = 0; i < 3; i++)
    {
        unsigned long holdseed = seed;
        seed ^ = << 13;
        seed ^ = seed >> 17;
        seed ^ = seed << 5;
        long r = (Int64)(holdseed + seed);
        sum + = (double)r * (1.0/0x7FFFFFFFFFFFFFFF);
    }
    return sum; //returns [-3.0, 3.0] at (66.7%, 95.8%, 100%)
}

I think I have a rough idea of how the bit shifting and XORing produces pseudo-random numbers and I understand how the summation gives a rough Gaussian distribution. What I don't understand is the expression (double)r * (1.0/0x7FFFFFFFFFFFFFFF). I imagine there is some bit or casting trick going on here, but I'm not sure what it is. Why do this division and then multiplication?




Aucun commentaire:

Enregistrer un commentaire