Last active
May 18, 2024 00:09
-
-
Save starfys/aaaee80838d0e013c27d to your computer and use it in GitHub Desktop.
Fast inverse square root in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@emre-aki
Additional speed can be obtained by:
const
tolet
function () {...}
to() => {...}
let x = f32[0] = number