John Carmack’s Unusual Fast Inverse Square Root (Quake III)

FYI. Carmack didn’t write it. Terje Mathisen and Gary Tarolli both take partial (and very modest) credit for it, as well as crediting some other sources.

How the mythical constant was derived is something of a mystery.

To quote Gary Tarolli:

Which actually is doing a floating
point computation in integer – it took
a long time to figure out how and why
this works, and I can’t remember the
details anymore.

A slightly better constant, developed by an expert mathematician (Chris Lomont) trying to work out how the original algorithm worked is:

float InvSqrt(float x)
{
    float xhalf = 0.5f * x;
    int i = *(int*)&x;              // get bits for floating value
    i = 0x5f375a86 - (i >> 1);      // gives initial guess y0
    x = *(float*)&i;                // convert bits back to float
    x = x * (1.5f - xhalf * x * x); // Newton step, repeating increases accuracy
    return x;
}

In spite of this, his initial attempt a mathematically ‘superior’ version of id’s sqrt (which came to almost the same constant) proved inferior to the one initially developed by Gary despite being mathematically much ‘purer’. He couldn’t explain why id’s was so excellent iirc.

Leave a Comment