fast inverse square root (v5)

Revision 5 of this benchmark created on


Description

testing fast inverse square root vs Math.sqrt

from http://gamedev.stackexchange.com/questions/30727/implement-fast-inverse-square-root-in-javascript

and http://coffeescriptcookbook.com/chapters/math/fast-inv-square

Setup

var buf = new ArrayBuffer(Float32Array.BYTES_PER_ELEMENT);
    var fv = new Float32Array(buf);
    var lv = new Uint32Array(buf);
    var threehalfs = 1.5;
    
    function Q_rsqrt(number) {
      var x2 = number * 0.5;
      fv[0] = number;
      lv[0] = 0x5f3759df - ( lv[0] >> 1 );
      var y = fv[0];
      y = y * ( threehalfs - ( x2 * y * y ) );
    
      return y;
    }
    
    var nums = [];
    for(var i = 0; i < 10000; i++){
    nums.push(Math.random()*100);
    }
    
    var approx_const_32, approx_const_64, approx_const_quake_32, fastInvSqrt_typed;
    
    approx_const_quake_32 = 0x5f3759df;
    
    approx_const_32 = 0x5f375a86;
    
    approx_const_64 = 0x5fe6eb50c7aa19f9;
    
    fastInvSqrt_typed = function(n, precision) {
      var i, iter, y, _i;
      if (precision == null) {
        precision = 1;
      }
      y = new Float32Array(1);
      i = new Int32Array(y.buffer);
      y[0] = n;
      i[0] = 0x5f375a86 - (i[0] >> 1);
      for (iter = _i = 1; 1 <= precision ? _i < precision : _i > precision; iter = 1 <= precision ? ++_i : --_i) {
        y[0] = y[0] * (1.5 - ((n * 0.5) * y[0] * y[0]));
      }
      return y[0];
    };

Test runner

Ready to run.

Testing in
TestOps/sec
1/Math.sqrt
for(var i = 0; i < nums.length; i++){
var a = 1/Math.sqrt(nums[i]);
}
ready
Q_rsqrt()
for(var i = 0; i < nums.length; i++){
var a = Q_rsqrt(nums[i]);
}
ready
fastInvSqrt_typed p=1
for(var i = 0; i < nums.length; i++){
var a = fastInvSqrt_typed(nums[i],1);
}
ready
fastInvSqrt_typed p=2
for(var i = 0; i < nums.length; i++){
var a = fastInvSqrt_typed(nums[i],2);
}
ready
fastInvSqrt_typed p=10
for(var i = 0; i < nums.length; i++){
var a = fastInvSqrt_typed(nums[i],10);
}
ready
fastInvSqrt_typed p=2 int
for(var i = 0; i < nums.length; i++){
var a = fastInvSqrt_typed(Math.floor(nums[i]),10);
}
ready
fastInvSqrt_typed p=10
for(var i = 0; i < nums.length; i++){
var a = fastInvSqrt_typed(nums[i],10);
}
ready
fastInvSqrt_typed p=2 int
for(var i = 0; i < nums.length; i++){
var a = fastInvSqrt_typed(Math.floor(nums[i]),10);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.