Skip to content

Instantly share code, notes, and snippets.

@chjj chjj/fisqrt.js
Last active Mar 27, 2017

Embed
What would you like to do?
// 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
You can’t perform that action at this time.