JavaScript implements the arithmetic square root algorithm-super simple code, javascript Arithmetic

Source: Internet
Author: User

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 .!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.