r/learnprogramming • • Sep 29 '25

TIL about Quake III's legendary "WTF?" code

This is a wild piece of optimization from Quake III Arena (1999):

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 fuck? 
    y = * ( float * ) &i;
    y = y * ( threehalfs - ( x2 * y * y ) );
    
    return y;
}

Those are the actual comments. It calculates inverse square roots 4x faster than normal by treating float bits as an integer and using a "magic number" (0x5F3759DF). Nobody knew who wrote it for years, turned out to be Greg Walsh from the late 1980s.

Modern CPUs have dedicated instructions now, but this remains one of the most elegant low-level hacks ever written.

https://en.wikipedia.org/wiki/Fast_inverse_square_root

1.5k Upvotes

131 comments sorted by

View all comments

24

u/zd_3dgy Sep 29 '25

hash functions and rng generators have code like this too. I wonder how they come up with the magic numbers tho in 1980 without plotting software

20

u/Tricky-Sentence Sep 29 '25

Probably a healthy dose of booze when at their wits end with a problem.

2

u/Vandrel Sep 29 '25

At the Ballmer Peak.

0

u/Vandrel Sep 29 '25

At the Ballmer Peak.

11

u/KerPop42 Sep 29 '25

Early numerical computing was a lot more analytic. As an aeronautical engineer, you can always tell when computers get developed in any specific thread of aerodynamics study because it stops being something like,

to determine the thickness of a boundary layer on a curved surface, use this function to map the position along the curved surface to a position on a flat plate, then use the equation 5.2x/Re(x)0.5 if Re < 106 and 0.37x/Re(x)0.2 if Re > 107

and starts being

to determine the thickness of a boundary layer on a curved surface, look up the closest-looking NACA standard airfoil and use those numbers

So I imagine there's some extremely elegant calculus you can use to find your optimal starting guess over the [0,1] range