Fast inverse square root function

Content:

Original link: A viral X post has spotlighted one of programming's most legendary hacks: the fast inverse square root function from id Software's 1999 Quake III Arena game / LinkedIn.

What can I say. It works!

#include 
#include 

float Q_rsqrt( float number )
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;
    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;
    i  = 0x5f3759df - ( i >> 1 );
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );
    //y  = y * ( threehalfs - ( x2 * y * y ) );
    return y;
}

int main()
{
    for(int i = 1; i <= 10; i++)
    {
        float x = i * i + i + 1;
        float fx1 = 1.0f / sqrt(x);
        float fx2 = Q_rsqrt(x);
        printf("%2d %5.1f %7.5f %7.5f %7.5f\n", i, x, fx1, fx2, fx2 - fx1);

    }
    return 0;
}

One iteration:

 1   3.0 0.57735 0.57685 -0.00050
 2   7.0 0.37796 0.37744 -0.00052
 3  13.0 0.27735 0.27731 -0.00004
 4  21.0 0.21822 0.21812 -0.00010
 5  31.0 0.17961 0.17951 -0.00009
 6  43.0 0.15250 0.15224 -0.00026
 7  57.0 0.13245 0.13240 -0.00006
 8  73.0 0.11704 0.11704 -0.00001
 9  91.0 0.10483 0.10472 -0.00011
10 111.0 0.09492 0.09478 -0.00014

Two iterations (remove out comment):

 1   3.0 0.57735 0.57735 -0.00000
 2   7.0 0.37796 0.37796 -0.00000
 3  13.0 0.27735 0.27735 0.00000
 4  21.0 0.21822 0.21822 -0.00000
 5  31.0 0.17961 0.17961 -0.00000
 6  43.0 0.15250 0.15250 -0.00000
 7  57.0 0.13245 0.13245 -0.00000
 8  73.0 0.11704 0.11704 -0.00000
 9  91.0 0.10483 0.10483 -0.00000
10 111.0 0.09492 0.09492 -0.00000

Comments: