Skip to content

Instantly share code, notes, and snippets.

@robhinds
Created October 5, 2013 20:00
Show Gist options
  • Save robhinds/6845427 to your computer and use it in GitHub Desktop.
Save robhinds/6845427 to your computer and use it in GitHub Desktop.
//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