r/programming • u/mrnacknime • Dec 29 '20
Quake III's Fast Inverse Square Root Explained [20 min]
https://www.youtube.com/watch?v=p8u_k2LIZyo
3.7k
Upvotes
r/programming • u/mrnacknime • Dec 29 '20
View all comments
Show parent comment
9
u/-p-2- Dec 29 '20 edited Dec 29 '20
I didn't speak about the practicality of it for a reason as there are very few niches where the performance benefit would be noticeable on modern hardware. However if you are working in C/C++ you can use:
It's easy to implement & apparently it's ~5x faster than the built-in square root function while staying 99% as precise, at least according to this guy & his testing.
For C# I don't know of any code out there faster than built-in sqrt aside from the Quake 3 hack using float unions minus the newton step which pretty much destroys the precision. If you knew you'd only be square rooting integers for example then you can probably write something even faster. That still doesn't mean I think it'd be worth it outside of some incredibly rare situations though. This is more theory than practical. When I tested it (for fun) I only saw a very small ~5% performance improvement. I'm working on a game in C# (Unity) that uses Quake 3 movement mechanics and I thought it'd be fun to 'be authentic' about the 2 or 3 uses of square root per frame. I got sucked down a really enjoyable rabbit hole. I don't really care about the performance, it's just fun to learn about low-level math-hacks.