Fast inverse square root
Fast inverse square root in hexadecimal 0x5f3759df is used to count the
x½
The code implementation is from Quake III Arena source code :
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 ) ); // 1st iteration
//y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
example : consider the number x = 0.15625, for which we want to calculate 1/√x ≈ 2.52982. The first steps of the algorithm are illustrated below:
00111110001000000000000000000000 Bit pattern of both x and i
00011111000100000000000000000000 Shift right one position: (i >> 1)
01011111001101110101100111011111 The magic number 0x5f3759df
01000000001001110101100111011111 The result of 0x5f3759df - (i >> 1)
source :
http://en.wikipedia.org/wiki/Fast_inverse_square_root
http://www.quora.com/What-is-the-shortest-and-most-effective-code-ever-written/answer/David-Diamondstone