Home >Web Front-end >JS Tutorial >JavaScript implements arithmetic square root algorithm - super simple code_javascript skills

JavaScript implements arithmetic square root algorithm - super simple code_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:39:402786browse

A few days ago I saw a square root code from Thor's Hammer. The principle has been introduced in many places, so I won't go into details.

The source code is written in C language. After thinking about it, I found that such an algorithm can also 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;
}

Test:

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 result is still slower than the system library, and the accuracy is inherently low. But I'm satisfied.

The above is the implementation of the arithmetic square root algorithm using JavaScript. How about it? The code is very simple. Friends who need it, come and learn it. !

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn