Created
November 9, 2013 04:07
-
-
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.
This file contains hidden or 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
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