Home
Insert
Update snippet 'Fast inverse square root'
Title
Description
This is an implementation of the famous 'magic number' method of rapidly calculating (inverse) square roots. (See http://en.wikipedia.org/wiki/Fast_inverse_square_root.) In practice, this version is no faster in F# than using 1./sqrt(x). I've posted it as an example of how you can get down-and-dirty with the bits in F# if you need to.
Source code
// For comparison, the original-ish C code is this: // // 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 f***? // 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; // } // let fastInvSqrt (n : float32) : float32 = let MAGIC_NUMBER : int32 = 0x5f3759df let THREE_HALVES = 1.5f let x2 = n * 0.5f let i = MAGIC_NUMBER - (System.BitConverter.ToInt32(System.BitConverter.GetBytes(n), 0) >>> 1) let y = System.BitConverter.ToSingle(System.BitConverter.GetBytes(i), 0) y * (THREE_HALVES - (x2 * y * y)) // Examples: let x = fastInvSqrt 4.0f // Output: val x : float32 = 0.499153584f let x' = 1. / sqrt(4.0) // Output: val x' : float = 0.5
Tags
fast inverse square root; bitwise
fast inverse square root; bitwise
Author
Link
Reference NuGet packages
If your snippet has external dependencies, enter the names of NuGet packages to reference, separated by a comma (
#r
directives are not required).
Update