Quake3's Fast Inverse Square Root Function
Oh my:
float InvSqrt (float x){
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
According to one of the guys supposedly responsible for this (arguably) legendary piece of code, “it’s just Newton-Raphson iteration with a very clever first approx.” And if you’re interested, you can also read about why it works.