A few days ago saw a thunder from the hammer of the square root code, the principle of many introduced, do not repeat.
The source code is written in C language, I think that this 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 precision is low. But I'm satisfied.
The above is to use JavaScript arithmetic square root algorithm algorithm, how, the code is very simple, need friends to learn it quickly.