Skip to content

Instantly share code, notes, and snippets.

@ahafidi
Created October 16, 2019 12:59
Show Gist options
  • Save ahafidi/5106e2cf16fa3dcca4fed660e4bf3a51 to your computer and use it in GitHub Desktop.
Save ahafidi/5106e2cf16fa3dcca4fed660e4bf3a51 to your computer and use it in GitHub Desktop.
val tolerance = 0.00001
def isCloseEnough(x: Double, y: Double): Boolean =
Math.abs((x - y) / x) / x < tolerance
def fixedPoint(f: Double => Double)(firstGuess: Double) = {
def iterate(guess: Double): Double = {
val next = f(guess)
if (isCloseEnough(guess, next))
next
else
iterate(next)
}
iterate(firstGuess)
}
def averageDamp(f: Double => Double)(x: Double) = (x + f(x)) / 2
def my_sqrt(x: Double) = fixedPoint(averageDamp(y => x / y))(1.0)
Math.sqrt(2)
my_sqrt(2)
Math.sqrt(3)
my_sqrt(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment