Home > Article > Web Front-end > JavaScript implements an example analysis of finding the square root of floating point numbers based on Newton's iteration method
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. Next
The example in this article describes how to use JavaScript to find the square root of a floating point number based on Newton's iteration method. I share it with you for your reference. The details are as follows:
Today I saw a method on the Internet that uses Newton's iteration method to find the square root of floating point numbers. I found it very good and runs faster than the sqrt method that comes with some languages. , back it up here for later use, some changes have been made here.
The first isThe principle of Newton's iteration method:
For example, we require the square root of a, First guess an approximate value x at random, and then keep making x equal to the average of x and a/x. After a few iterations, the value of x will be 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 = ?
..
..
The following is implemented using JavaScript
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 4G.sqrt(2)
: The result is 1.414G.sqrt(100.2565)
Of course, there seem to be other implementations of the Newton iteration method on the Internet. Readers can choose the method that suits their own understanding according to their needs.
The above is the detailed content of JavaScript implements an example analysis of finding the square root of floating point numbers based on Newton's iteration method. For more information, please follow other related articles on the PHP Chinese website!