Skip to content

Instantly share code, notes, and snippets.

@chjj
Last active March 27, 2017 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chjj/f845b613bd6fd72b5ee978dae110b953 to your computer and use it in GitHub Desktop.
Save chjj/f845b613bd6fd72b5ee978dae110b953 to your computer and use it in GitHub Desktop.
// 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