+ 1

Who has this fastest sqrt finding advanced code running?

float Q_rsqrt( float number ) {  long i;  float x2, y;  const float threehalfs = 1.5F;    x2 = number * 0.5F;  y = number;  i = * ( long * ) &y; // evil floating point bit level hacking  i = 0x5f3759df - ( i >> 1 ); // what the fuck?   y = * ( float * ) &i;  y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration  // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed    return y; }

19th Aug 2017, 11:31 AM
Rifat
Rifat - avatar
2 Answers
+ 4
From Java.lang.StrictMath: public static double sqrt(double x) { if (x < 0) return Double.NaN; if (x == 0 || ! (x < Double.POSITIVE_INFINITY)) return x; // Normalize x. long bits = Double.doubleToLongBits(x); int exp = (int) (bits >> 52); if (exp == 0) // Subnormal x. { x *= TWO_54; bits = Double.doubleToLongBits(x); exp = (int) (bits >> 52) - 54; } exp -= 1023; // Unbias exponent. bits = (bits & 0x000fffffffffffffL) | 0x0010000000000000L; if ((exp & 1) == 1) // Odd exp, double x to make it even. bits <<= 1; exp >>= 1; // Generate sqrt(x) bit by bit. bits <<= 1; long q = 0; long s = 0; long r = 0x0020000000000000L; // Move r right to left. while (r != 0) { long t = s + r; if (t <= bits) { s = t + r; bits -= t; q += r; } bits <<= 1; r >>= 1; } // Use floating add to round correctly. if (bits != 0) q += q & 1; return Double.longBitsToDouble((q >> 1) + ((exp + 1022L) << 52)); }
19th Aug 2017, 3:57 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
Thanks a lot.
20th Aug 2017, 12:50 AM
Rifat
Rifat - avatar