Created
October 5, 2013 20:00
-
-
Save robhinds/6845427 to your computer and use it in GitHub Desktop.
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
//Improve the guess using Newton's method | |
def improve = { guess, x -> | |
(guess + x / guess) / 2 | |
} | |
//Check if our guess is good enough, within a chosen threshold | |
def isGoodEnough = {guess, x -> | |
abs(guess * guess - x) < 0.001 | |
} | |
//iterate over guesses until our guess is good enough | |
def sqrtIter = { guess, x -> | |
if (isGoodEnough(guess, x)) guess | |
else sqrtIter(improve(guess, x), x) | |
} | |
//wrap everythin in the square root function call | |
def sqrt = {x -> srqtIter(1.0, x)} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment