Home > Web Front-end > JS Tutorial > Detailed explanation of how to find the square root of a floating point number using JavaScript

Detailed explanation of how to find the square root of a floating point number using JavaScript

小云云
Release: 2018-02-01 09:21:03
Original
2545 people have browsed it

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 = ?
..
..

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/>";
  }
 }
};
Copy after login

Run

G.sqrt(16) : The result is 4
G.sqrt(2) : The result is 1.414
G.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.

Related recommendations:


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template