sqrt(x) and 1/sqrt(x)

Popular way to approximate sqrt(x) and 1/sqrt(x):


  public static float isqrt(float x)
  {
    float hx = x * 0.5f;
    int   ix;
    float r;

    // make initial guess
    ix = Float.floatToRawIntBits(x);
    ix = 0x5f3759df - (ix>>1);
    r  = Float.intBitsToFloat(ix);

    // do some number of newton-ralphson steps,
    // each doubles the number of accurate
    // binary digits.
    r  = r*(1.5f-hx*r*r);
  //r  = r*(1.5f-hx*r*r);
  //r  = r*(1.5f-hx*r*r);
  //r  = r*(1.5f-hx*r*r);

    return r;    // 1/sqrt(x)
  //return r*x;  // sqrt(x)
  }


Here’s some background on how this technique works: http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/

very nice

EDIT : tested… and unfortunatly due to the slowness of Float.floatToIntBits(x) it seems to doesn’t give any performance gain

replace
Float.floatToIntBits()

by
Float.floatToRawIntBits()

maybe it speeds up the ‘conversion’

Yeah, I just logged in to note using ‘raw’ instead comment (bad me). The ‘guess’ part can be changed to something else (such as a small table for limited ranges).

Another thing to note is for renormalizing vectors, quaternions, etc. … the guessed value is ‘1’ and normally a single N-R step will commonly give you the renormalization multiplier.

(edit: many typos)