Skip to content

Instantly share code, notes, and snippets.

@starfys
Last active May 18, 2024 00:09
Show Gist options
  • Save starfys/aaaee80838d0e013c27d to your computer and use it in GitHub Desktop.
Save starfys/aaaee80838d0e013c27d to your computer and use it in GitHub Desktop.
Fast inverse square root in Javascript
//Based on the fast inverse square root function
// https://en.wikipedia.org/wiki/Fast_inverse_square_root
// Some original comments preserved for humor value
// Designed to try to mimic the original as closely as possible
function Q_rsqrt(number)
{
var i;
var x2, y;
const threehalfs = 1.5;
x2 = number * 0.5;
y = number;
//evil floating bit level hacking
var buf = new ArrayBuffer(4);
(new Float32Array(buf))[0] = number;
i = (new Uint32Array(buf))[0];
i = (0x5f3759df - (i >> 1)); //What the fuck?
(new Uint32Array(buf))[0] = i;
y = (new Float32Array(buf))[0];
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
@mlhaufe
Copy link

mlhaufe commented May 18, 2024

@emre-aki

Additional speed can be obtained by:

  1. Converting const to let
  2. Convert function () {...} to () => {...}
  3. Inline the assignment: let x = f32[0] = number
  4. making sure you are in strict mode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment