Skip to content

Instantly share code, notes, and snippets.

@lynxluna
Created January 21, 2012 13:12
Show Gist options
  • Save lynxluna/1652740 to your computer and use it in GitHub Desktop.
Save lynxluna/1652740 to your computer and use it in GitHub Desktop.
Fast Inverse Square Root Without Pointer Casting
/* See http://en.wikipedia.org/wiki/Fast_inverse_square_root for
For original implementation
*/
typedef union {
long l;
float f;
} LongFloat;
static inline float InvSqrt( const float v ) {
LongFloat i, x2, y;
const float threehalfs = 1.5f;
x2.f = v * 0.5f;
y.f = v;
i.f = y.f; // evil floating point bit level hacking
i.l = 0x5f3759df - ( i.l >> 1 ); // what the fuck?
y.f = i.f;
y.f = y.f * ( threehalfs - ( x2.f * y.f * y.f ) ); // 1st iteration
y.f = y.f * ( threehalfs - ( x2.f * y.f * y.f ) ); // 2nd iteration
return y.f;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment