Tππ π³πππ ππππ πππππππ
πππ πππππππ ππ ππππ π°ππππππ πΊπππππ πΉπππ
iΒ = 0x5f3759df – ( i >> 1 );Β Β Β Β Β Β Β Β // what the fuck?
It is not my comment, but the comment made by some programmer that passed through the code review during the 90’s and the one which is available online right now.
A Brief History about that line:
The line belongs to the function Q_rsqrt() which is a clever piece of software engineering that calculates 1/sqrt(x).
Traditionally, the computation of the inverse square root of a number, which is needed for operations like normalizing vectors, was a computationally intensive task. This was especially true for 3D graphics applications and games, which require such calculations to be done many times per second for lighting, reflections, and physics simulations.
The “Fast Inverse Square Root” function uses a method of bit manipulation and approximation to compute the inverse square root very quickly. The core of the trick lies in the line i = 0x5f3759df – ( i >> 1 );, which is an application of Newton’s method for estimating the roots of a real-valued function. Here, a magical constant 0x5f3759df is used to get an initial approximation of the inverse square root, which is then refined with just one iteration of Newton’s method.
This function was revolutionary at the time because it allowed for much more efficient graphics processing, which was particularly beneficial in the era when processor speed and capabilities were much more limited than they are today. By making such operations faster, games could run more smoothly with more complex graphics. It’s a testament to the ingenuity of game developers and their ability to push the boundaries of hardware limitations.
Beyond its technical prowess, the Fast Inverse Square Root became a piece of programming folklore. Its conciseness and the use of the ‘magic number’ have sparked discussions, debates, and admiration in equal measure. It’s a piece of hacker artistry that reflects a deep understanding of both mathematics and machine.
The Fast Inverse Square Root function may have been a product of its time, yet its legacy endures. It is a reminder that sometimes, the most impactful solutions come from thinking outside the conventional bounds, armed with a deep understanding of the tools at our disposal.
Code source: https://github.com/id-Software/Quake-III-Arena/blob/master/code/game/q_math.c#L552
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 ) );Β Β // 1st iteration
return y;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Article Written By: Yashwanth Naidu Tikkisetty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
