Crazy inverse square root code

Can you understand how this works?

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;
}

There are some crazy approximations in that code that take use of the x86 architecture and implementation details of IEEE floating point. It popped up in the open-source Quake 3 code base but apparently has a history going much further back.

An author at Beyond3D spent some time trying to figure out who wrote the code. Here’s the article on his findings. Pretty crazy. And for the record, no, I don’t understand how the math in that function actually works. It is pretty cool though.

Leave a Reply