Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Created November 9, 2013 04:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save animatedlew/7381483 to your computer and use it in GitHub Desktop.
Save animatedlew/7381483 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