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

501

u/theBarneyBus Sep 29 '25

To be pedantic, it doesn’t calculate an inverse square root, it approximates it (within a small single-digit percent margin of error).

The slight inaccuracies lead to a slightly non-perfect FOV & “framing” of each rendered frame, but it’s close enough to not matter.

208

u/WasteKnowledge5318 Sep 29 '25

It does indeed approximate. Engineering is all about approximations and tolerances.

We can only ever get an `approximate` value of the area of a circle. :)

48

u/sonofaresiii Sep 29 '25

No man we can get an exact area of a circle. It's the radius squared times pi. Exactly.

What we have to approximate is its expression as a decimal.

15

u/WasteKnowledge5318 Sep 29 '25

Sure, we can get the exact area: it's πr². Easy! Now if you want me to actually tell you what that number is... well, that's where things get approximate. The math is perfect; our number system just wasn't invited to the party.

11

u/geon Sep 29 '25

pi is a number.

6

u/WasteKnowledge5318 Sep 29 '25

An irrational and transcendental one

→ More replies (1)
→ More replies (6)

31

u/grepTheForest Sep 29 '25

If you use base pi then it's not approximate.

Say the radius is 1. Then the area is 10.

12

u/XenophonSoulis Sep 29 '25

Good luck explaining that to a computer (they only understand base 2).

→ More replies (11)
→ More replies (2)
→ More replies (11)

169

u/afineedge Sep 29 '25

Excuse me, but my country has a nearly infinite coastline thanks to this. 

→ More replies (3)

2

u/florinandrei Sep 29 '25

I approximately agree with your comment, and I think it can be tolerated.

15

u/DustRainbow Sep 29 '25

Well to be really pedantic square roots can be irrational so it will always be approximate in a finite decimal system.

2

u/captainAwesomePants Sep 29 '25

And, worse, Quake 3 floating point numbers aren't just finite, they're at most 24 base 2 digits of precision (plus an exponent).

1

u/debau24 Sep 29 '25

Everything is an approximation on a digital computer with finite bit precision

34

u/ruat_caelum Sep 29 '25

To be far the

y = y * ( threehalfs - ( x2 * y * y ) );

was used twice (though using it once on the domain supplied is less than 1% error across the span, so it was actually:

y = y * ( threehalfs - ( x2 * y * y ) );
y = y * ( threehalfs - ( x2 * y * y ) );
return y;

9

u/A-Grey-World Sep 29 '25

I always thought the second iteration was commented out?

13

u/Alarming_Chip_5729 Sep 29 '25

It was, with another comment about doing another iteration improved the accuracy by some small margin, but i dont remember exactly what

Edit: actually, it is commented out with a comment that says "2nd iteration, this can be removed"

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.

→ More replies (1)

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

13

u/derpbynature Sep 29 '25

What exactly does the "magic number" do here?

15

u/xill47 Sep 29 '25

It's not a single thing. Interpreting floats as ints gives you ability to manipulate exponent, so it's kinda similar to logarithm. The number takes a bunch of related constants so we can calculate approximation of -1/2log_2(x) and correctly transform it back.

0

u/rstr1212 Sep 29 '25

What's an 'ints'?

3

u/Usual_Ice636 Sep 29 '25

"ints" is the plural of int, which stands for integer. Its a data type in some types of programming.

1

u/TrueTorch Sep 29 '25

integers. numbers.

3

u/cantaloupelion Sep 29 '25

uh.. i dont really understand it but i think it helps with teh approximation??

this links here explains it quite well https://h14s.p5r.org/2012/09/0x5f3759df.html?mwh=1

and that links appendix lol. https://h14s.p5r.org/2012/09/0x5f3759df-appendix.html

132

u/inline_five Sep 29 '25

Back when men were men and programmers were programmers and knew what a pointer was

10

u/Spinning_Rings Sep 29 '25

And small, furry things from alpha centauri were small, furry things from alpha centauri

1

u/captainAwesomePants Sep 29 '25

Now here's a man who really knows where his towel is.

6

u/ruat_caelum Sep 29 '25

worse they knew how to cast a pointer into some other type!!

3

u/DescriptorTablesx86 Sep 29 '25

I hope the other type is still a pointer otherwise maybe you should be using assembly at this point lmao

1

u/ruat_caelum Sep 30 '25

They manipulated a constructed type. e.g. the float, and treated it like a binary number because some of log base 2 weird math.

It was clever

1

u/flatfinger Oct 01 '25

Assembly language is unfortunately very toolset specific. I think it would be more useful to have a means of writing platform-specific code in toolset-agnostic fashion, perhaps with a syntax that's just like a language Dennis Ritchie invented.

4

u/DustRainbow Sep 29 '25 edited Sep 29 '25

I'm a noob

1

u/RenderTargetView Sep 29 '25

They literally are not casting, they interpret bits of float value as integer value, explicit casting would give number with different bits

2

u/DustRainbow Sep 29 '25

Yeah correct, I spoke too fast. Will edit out.

6

u/Paul_Offa Sep 29 '25

Imagine asking a Gen-Z 'vibe coder' to try and solve the issue they were having.

6

u/IncreaseOld7112 Sep 29 '25

optimization is different these days. The (cpu and gpu) processor spends most of its time waiting for main memory.

1

u/phlogistonical Sep 29 '25

Computers have become so stupidly fast, 9 of 10 times the most naive non-optimised approach is good enough these days. Not great, mind you, just good enough. Wirth's law is still applicable.

3

u/[deleted] Sep 29 '25

What work do you do where people don't know what a pointer is

4

u/dandandan2 Sep 29 '25

Ask vibe coders

2

u/WJMazepas Sep 29 '25

There still are low-level programmers that work in C, C++, Rust, Zig. Hell, a guy created the Beef programming language, a low-level language, specifically for games recently

And all those AAA games today are made with low-level languages.

This comment really doesn't make sense

-5

u/giantgreeneel Sep 29 '25

Are you twelve

0

u/[deleted] Sep 29 '25

[deleted] — view deleted comment

8

u/CertainlySnazzy Sep 29 '25

thats so much worse

0

u/[deleted] Sep 29 '25

[deleted] — view deleted comment

113

u/tru_anomaIy Sep 29 '25

Those games are optimised though.

It’s just that they’re optimised for release date and developer cost, not framerate

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.

12

u/dkarlovi Sep 29 '25

I can't understand how people don't understand that. Making game engines is not making games, most of the bangers you've played, the devs used a ready made engine, it's just they've used it well. If you need to make the engine to make the game, you're driving the train tracks as you're laying them.

→ More replies (1)

15

u/sellibitze Sep 29 '25

Yeah, it's cool. Just let me add two things:

  1. It's possible to tweak this magic constant in order to improve the overall approximation error. I've done so manually and I've seen a blog article where the author performed an automated search to minimize the worst case relative error.
  2. This code actually invokes undefined behaviour. Last time I tested it using GCC it stopped working with optimizations turned on. Specifically, the code violates the strict aliasing rules. A compiler is allowed to assume that an int* and a float* do not alias the same memory location. Instead, a memcpy would be fine.

7

u/WJMazepas Sep 29 '25

Yeah, this code was cool for the 90s, but today, we have better algorithms with more accuracy and the same or even better performance

But also, so many C code have "hacks" that are against the rules, especially when talking about old code and modern compilers

1

u/Kajitani-Eizan Oct 01 '25

Better performance? Using what, architecture extension instructions?

2

u/835246 Sep 29 '25

A union can also be used to get around strict aliasing.

1

u/blazesbe Sep 30 '25

if you look at a breakdown of how quake/doom architecture worked you will see that ID had "absolutely no respect for the language" in a good sense. they only cared what the assembly does under. wanna know why doom can be ported on all platforms? because it's made absolutely modular. the rendering isn't "baked in" but a separate component. also they didn't have "lua" back then for scripting. they used C code and a C compiler to make (in a modern sense) scripting logic into assembly code, which their lightweight game engine/VM interpreted. i may be mixing some things up but ID software guys are wizzards for a reason.

10

u/scratch31415 Sep 29 '25

But why do: i = * (long *) &y And not just: i = y ?

Will probably be facepalming in 2 mins

27

u/DirkSwizzler Sep 29 '25

i is type long (32 but integer in this context) y is type float

Doing a direct assignment tells the compiler to round/truncate the decimal portion away to fit in an integer. I believe the exact conversion is controlled by CPU register settings at runtime.

The "*(long *)&y" tells the compiler to treat the raw bits as something that's already converted. it will most assuredly be some crazy value that does not reflect the floating point value at all. But it lets you do bit manipulation for real wizardy

15

u/risanaga Sep 29 '25 edited Sep 29 '25

It's called type punning. Just saying i = y takes the float value of y, truncates the decimal, and that becomes the integer. This reference/pointer cast effectively copies the bits as-is in the float. No truncating or type conversion.

As an actual example, the float value of -0 regularly converted to a long just becomes 0. This type pun gets you the value of -maxint.

Edit: just to add something. This is not normally something that should be done. It's a subversion of the type system that usually ends up being UB. It's occasionally necessary though

3

u/Lithl Sep 29 '25

Assume y = 3.5

If you do i = y, then i = 3.

If you do i = * (long *) &y, then i = 1080033280.

3

u/FiTroSky Sep 29 '25

Wonder how much more faster some modern game would be if we allowed more "approximations".

3

u/nmkd Sep 29 '25

Everything, absolutely everything is an approximation in modern games.

That's one of the reasons many of them rely on temporal accumulation so much - to even out the errors from the approximated outputs.

3

u/WJMazepas Sep 29 '25

We have so many approximations already. Everything concerning lighting, shadows are just approximations. And you can notice that in many games that have light "leak" where it wasnt supposed to

1

u/FiTroSky Sep 29 '25

Hmm, now that you mention it.

2

u/ShustOne Sep 29 '25

As mentioned by others, there are lots of approximations used to this day. The code above is actually no longer used as we have faster ways of getting better approximations now too. Approximations are awesome.

3

u/batclocks Sep 29 '25

There’s this guy who only has one YouTube video on his whole channel, and it’s just a really detailed interesting breakdown of this algorithm.

2

u/Sebbean Sep 30 '25

Which guy

1

u/batclocks Sep 30 '25

https://youtu.be/p8u_k2LIZyo?si=BV8uZKYNQ1jObAKL

He’s got a few other videos now. Still a great watch, and I’m not the only one who thought so (5.6 million views at time of writing)

2

u/crispyfunky Sep 29 '25

Give this guy an HPC performance optimization job and a custom ASIC

2

u/Xiten Sep 29 '25

Loved quake 3. id Tech 3 is amazing.

2

u/turtleXD Sep 29 '25

not too long ago i did an exercise where I basically applied this same black magic, but for the normal square root instead. forced me to really understand how it worked. awesome stuff

2

u/TrevorLaheyJim Oct 02 '25

All of us have at some point accidentally committed something like this by accident.

Code Reviews don't always catch it.

1

u/Sakkyoku-Sha Oct 02 '25

I always found it super interesting that this isn't true on modern CPUs and compilers. 

You can benchmark this in C today, and it won't be faster than other commonly used methods. 

0

u/Nixinova Sep 29 '25

Im still confused why they saved "three halfs" to a variable as if that's gonna change, meanwhile 0xNonsense gets to just sit as a magic number, lol

-4

u/RedditWishIHadnt Sep 29 '25

I think this caused problems when open sourcing the code as someone else had copyrighted this trick some time after Quake was released so it had to be rewritten.

1

u/Vagina_Titan Sep 29 '25

Did that other person come up with this trick too with their own methods? Or did they steal it? Or perhaps was this trick something that made its way around by word of mouth?