Home >Web Front-end >JS Tutorial >Detailed explanation of how to find the square root of a floating point number using JavaScript
This article mainly introduces JavaScript to realize the square root of floating point numbers based on Newton's iteration method. It briefly explains the principle of Newton's iteration method, and analyzes the related operation skills of JavaScript's recursive numerical operations based on examples. Friends who need it can refer to it. I hope Can help everyone.
I saw a method on the Internet today that uses the Newton iteration method to find the square root of a floating point number. I found it to be very good. It runs faster than the sqrt method that comes with some languages. I will back it up here for later use. , some changes have been made here.
The first is the principle of Newton's iteration method:
For example, if we ask for the square root of a, we first guess an approximate value x, and then continue to make x is equal to the average of x and a/x. After a few iterations, the value of x is already quite accurate. For example, the mathematical hypothesis we require is a=7, var x=a;( 7 + 7/7 ) / 2 = 3.64287514 ( 3.64287514 + 7/3.64287514 ) / 2 = ?
..
..
var G={ result:0 ,sqrt:function(a){ var x=a; for(var i=0;i<=Math.floor(a);i++) { x=(x+a/x)/2; if(x-this.result===0){ //用来减少循环次数 break; } this.result=x; document.body.innerHTML+="this.result-->"+this.result+"-->X:"+x+"<br/>"; } } };Run
G.sqrt(16) : The result is 4
G.sqrt(2) : The result is 1.414
G.sqrt(100.2565)
Sharing examples of solving inaccurate floating point number operations in PHP
Accurate calculation of js floating point numbers
How to solve js floating point number precision issues
The above is the detailed content of Detailed explanation of how to find the square root of a floating point number using JavaScript. For more information, please follow other related articles on the PHP Chinese website!