Code: Select all
float fastInvSqrt(float x)
{
float halfx(0.5f*x);
union {
float f;
uint32_t l;
}i;
i.f = x;
i.l = 0x5f3759df - (i.l>>1);
i.f = i.f*(1.5f - halfx*i.f*i.f);
return i.f;
}
It calculates x^(-1/2) which is the inverse square root.
It's extremely useful when you want to normalize a set of vectors.
Normaly you would do this:
Code: Select all
n = sqrt(a+b+c)
a = a/n
b = b/n
c = c/n
With this little puppy you do this:
Code: Select all
n = fastInvSqrt(a+b+c)
a = a * n
b = b * n
c = c * n
It's fantastically cool because:
1) It calculates the approximate value. That is, a value that is very close to the real one. It does this much much faster too.
2) It allows us to use multiplications instead of divisions - neat again
3) It includes some of the deepest most intriguing bit hacks I have ever seen.
Truly the work of serious masters. I am in awe!