▇ In this post I will talk about one of the most famous pieces of code optimisation that can be written in a single line of code. It can be found in the source code of the first-person shooter Quake 3, and is probably the reason why it got so much public attention. It involves the calculation of the inverse square root of a floating point number. See also the bibliography of the Wikipedia article Fast inverse square root for more information. Here is the code:
1: float InvSqrt (float x) { 2: float xhalf = 0.5f*x; 3: long i = *(long*)&x; 4: i = 0x5F83759DF - (i>>1); //initial guess of inv-sqr 5: x = *(float*)&i; 6: x = x*(1.5f-xhalf*x*x); //one step of newton iteration 7: return x; 8: } |
A single execution of this InvSqrt-Function yields a very good approximation to the inverse square root. It is said, that it is $4$-times faster than the native division method (float)((1.0)/sqrt(x)).