r/learnprogramming • u/WasteKnowledge5318 • 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.
1.5k
Upvotes
View all comments
Show parent comment
37
u/Mike312 Sep 29 '25
That's exactly it. A lot of things get pushed into libraries, frameworks, or - in gaming - pre-made engines because otherwise it's just an absolute ton of work.
My friend built a game engine for a game he was trying to make in the ~2000s; took him 3 years to write the engine. He could have spent those 3 years on actually making the game.
Also, the skillset for a good game engine isn't necessarily the same skillset required to make a fun, balanced, good-looking game.