JavaScript implements the arithmetic square root algorithm-super simple code, javascript Arithmetic
A few days ago, I saw a square root source code from Raytheon. I will not go into details about the principles.
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); 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.000msVM2303: 24 t: 16720.000 ms
Although the results are still slower than the system database, and the accuracy is inherently low. But I'm very satisfied.
The above describes how to use javascript to implement the arithmetic square root algorithm. The code is very simple. Come and learn it .!