Created
January 6, 2019 05:07
-
-
Save jiggzson/0c5b33cbcd7b52b36132b1e96573285f to your computer and use it in GitHub Desktop.
Calculate the square root using Newton's method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sqrt(n) { | |
var xn, d, ld; | |
var c = 0; //counter | |
var done = false; | |
var delta = 1e-17; | |
xn = n/2; | |
var safety = 1000; | |
do { | |
//break if we're not converging | |
if(c > safety) | |
throw new Error('Unable to calculate square root for '+n); | |
xn = (xn+(n/xn))/2; | |
//get the difference from the true square | |
d = n - (xn*xn); | |
//if the square of the calculated number is close enough to the number | |
//we're getting the square root or the last delta was the same as the new delta | |
//then we're done | |
if(Math.abs(d) < delta || ld === d) | |
done = true; | |
//store the calculated delta | |
ld = d; | |
c++; //increase the counter | |
} | |
while(!done) | |
return xn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment