Last active
March 27, 2017 21:35
-
-
Save chjj/f845b613bd6fd72b5ee978dae110b953 to your computer and use it in GitHub Desktop.
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
// Fast inverse square root in javascript | |
// https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code | |
// Example: | |
// > 1 / Math.sqrt(0.15625) | |
// 2.5298221281347035 | |
// > Math.pow(0.15625, -0.5) | |
// 2.5298221281347035 | |
// > Q_rsqrt(0.15625) | |
// 2.5254863388218056 | |
var b = new Buffer(4); | |
function Q_rsqrt(number) { | |
var i, x2, y; | |
var threehalfs = 1.5; | |
x2 = number * 0.5; | |
y = number; | |
b.writeFloatBE(y, 0); | |
i = b.readInt32BE(0); // evil floating point bit level hacking | |
i = 0x5f3759df - (i >>> 1); // what the fuck? | |
b.writeInt32BE(i, 0); | |
y = b.readFloatBE(0); | |
y = y * (threehalfs - (x2 * y * y)); // 1st iteration | |
// y = y * (threehalfs - (x2 * y * y)); // 2nd iteration, this can be removed | |
return y; | |
} | |
console.log(Q_rsqrt(0.15625)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment