title: John Carmack's Unusual Fast Inverse Square Root (Quake III)
body: <p>John Carmack has a special function in the Quake III source code which calculates the inverse square root of a float, 4x faster than regular <code>(float)(1.0/sqrt(x))</code>, including a strange <code>0x5f3759df</code> constant. See the code below. Can someone explain line by line what exactly is going on here and why this works so much faster than the regular implementation?</p>
  
  <pre class="lang-c prettyprint-override"><code>float Q_rsqrt( float number )
  {
    long i;
    float x2, y;
    const float threehalfs = 1.5F;
  
    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &amp;y;
    i  = 0x5f3759df - ( i &gt;&gt; 1 );
    y  = * ( float * ) &amp;i;
    y  = y * ( threehalfs - ( x2 * y * y ) );
  
    #ifndef Q3_VM
    #ifdef __linux__
      assert( !isnan(y) );
    #endif
    #endif
    return y;
  }
  </code></pre>