JavaScript implements arithmetic square root algorithm the code is super simple

  • 2020-08-22 21:43:55
  • OfStack

A few days ago I saw a square root source code from the hammer of Thor, the principle of more than one introduction, do not elaborate.

The source code is written in c language. After thinking about it, I found that such an algorithm can be completed in javascript.


function InvSqrt(x){
  var h=0.5*x;
  var b=new ArrayBuffer(4);
  var d=new DataView(b,0);
  d.setFloat32(0,x);
  var i=d.getInt32(0);
  i=0x5f375a86-(i>>1);
  d.setInt32(0,i);
  var r=d.getFloat32(0);
  r=r*(1.5-h*r*r);
  return r;
}

Testing:


console.time("t");
for(var i=0;i<10000000;i++){
 InvSqrt(i);
}
console.timeEnd("t");

console.time("t");
for(var i=0;i<10000000;i++){
 1/Math.sqrt(i);
}
console.timeEnd("t");
VM2303:18 t: 33438.000ms
VM2303:24 t: 16720.000ms

Although the results are still slower than the system library, and the accuracy is inherently low. But I'm satisfied.

Above is to use javascript to achieve the arithmetic square root algorithm algorithm, how, the code is very simple, the friends need to learn quickly. !


Related articles: