7 Oct 2008

0x5f3759df & a few thoughts

It was during a recent visit to some game development forums that I chanced upon this piece of code ( from the Doom / Quake codebase - Now that Quake3 v1.32 source has been GPL'ed ). As it is with any piece of Doom/Quake - it was immediately attributed to the legendary John Carmack.

However someone did dig deep into it (http://www.beyond3d.com/content/articles/8/) to identify who exactly (or approximately) was responsible for this brilliant hack for computing the inverse square root.

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;

Anyway, it is not the history that interests me here. It is the brilliance of the method used in the above snippet. After going through it - especially the 0x5f3759df - (i>>1) part, I feel I should have paid more attention to mathematics in those computer science classes - when they taught the Newton Raphson method (For those who wish to understand what I'm talking about - just googling for 0x5f3759df should throw up enough suitable explanations).

But then - when I try going back in time and visualizing those days more clearly - I realise it was a problem with the educational framework itself . Mathematics in the computer science curriculum was never made to look interesting as such. Computational theory & numerical analysis techniques were never explained with solution domains articulated. Professors stuck to just reading out textbook prose. So everything just remained a formula that students mastered & applied to a few textbook examples. I'm not passing the blame - but this sad state of affairs has lead to a generation of application programmers but not computer scientists.

But now, with open-source and the www, more & more opportunities are there for everyone - who missed the boat. Catch up and reinforce old learned stuff & find innovative applications.

I'll keep posting any more of such interesting snippets that I come across.

1 comment :

  1. Sahi hai ! cool technique.. I should be checking out the Quake codebase for more gems like this one.