Skip to content

Instantly share code, notes, and snippets.

@jiggzson
Created January 6, 2019 05:07
Show Gist options
  • Save jiggzson/0c5b33cbcd7b52b36132b1e96573285f to your computer and use it in GitHub Desktop.
Save jiggzson/0c5b33cbcd7b52b36132b1e96573285f to your computer and use it in GitHub Desktop.
Calculate the square root using Newton's method
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