Skip to content

Instantly share code, notes, and snippets.

@casoetan
Forked from animatedlew/sqrt.js
Created August 28, 2018 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save casoetan/23dafa27f92ca5b019227b2e8c0de7c1 to your computer and use it in GitHub Desktop.
Save casoetan/23dafa27f92ca5b019227b2e8c0de7c1 to your computer and use it in GitHub Desktop.
Here is an implementation of a square root function in JavaScript using Newton's method.
var sqrt = function(x) {
var isGoodEnough = function(guess) {
return Math.abs(guess * guess - x) / x < 0.001;
};
var improve = function(guess) {
return (guess + x / guess) / 2;
};
var sqrIter = function(guess) {
return (isGoodEnough(guess)) ? guess : sqrIter(improve(guess))
};
return sqrIter(1.0);
};
console.log(
Math.sqrt(1000),
sqrt(1000)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment