fast inverse square root explained

Fast Inverse Square Root in C

The fast inverse square root algorithm is a method for approximating ( \frac{1}{\sqrt{x}} ) for a 32-bit floating-point number x in C. It is commonly associated with the Quake III Arena game and is known for its clever use of bit manipulation and the magic constant 0x5f3759df.

The algorithm is as follows:

float Q_rsqrt( float number )
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  =  ( long  ) &y;                       // evil floating point bit level hacking
    i  = 0x5f3759df - ( i >> 1 );               // what the hell?
    y  =  ( float  ) &i;
    y  = y  ( threehalfs - ( x2  y * y ) );   // 1st iteration
    // y  = y  ( threehalfs - ( x2  y * y ) ); // 2nd iteration, this can be removed

    return y;
}

Note: This algorithm is an example of a fast approximation and may not provide the same level of accuracy as the standard library function.

[[SOURCE #1]]