Skip to content

Instantly share code, notes, and snippets.

@Jabher
Created July 25, 2015 23:00
Show Gist options
  • Select an option

  • Save Jabher/2300ba0ffe33fec48ea5 to your computer and use it in GitHub Desktop.

Select an option

Save Jabher/2300ba0ffe33fec48ea5 to your computer and use it in GitHub Desktop.
Fast inverse square root. Identical to https://en.wikipedia.org/wiki/Fast_inverse_square_root description.
/**
* As close as possible transfer of https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code
*/
const dataView = new DataView(new ArrayBuffer(8));
const intVars = new Int32Array(4);
const floatVars = new Float32Array(4);
const intConsts = new Int32Array(1);
const floatConsts = new Float32Array(2);
intConsts[0] = 0x5f3759df;
floatConsts[0] = 1.5; //threehalfs
floatConsts[1] = 0.5; //onehalf
export function fisqrt (n, p = 1) {
floatVars[0] = n;
floatVars[1] = floatVars[0] * floatConsts[1];
dataView.setFloat32(0, floatVars[1]);
intVars[0] = dataView.getInt32(0); // evil floating point bit level hacking
intVars[1] = intConsts[0] - (intVars[0] >> 1); // what the fuck?
dataView.setInt32(0, intVars[1]);
floatVars[2] = dataView.getFloat32(0);
floatVars[2] = floatVars[2] * (floatConsts[0] - (floatVars[1] * floatVars[2] * floatVars[2])); // 1st iteration
//floatVars[2] = floatVars[2] * (floatConsts[0] - (floatVars[1] * floatVars[2] * floatVars[2])); // 2nd iteration, this can be removed
return floatVars[2];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment