Tail-recursive version from Prof. Martin Odersky’s online course

I made it into a recursive version as an exercise.

def tolerance = 0.0001 def isCloseEnough(x: Double, y: Double) = { (abs(x-y))/x/x < tolerance } def averageDamp (f: Double => Double)(x: Double) = (x + f(x))/2 def fixedPointTail(f: Double => Double)(firstGuess: Double): Double ={ def loop(guess: Double): Double = { println("guess = " + guess) val nextGuess = f(guess) if (isCloseEnough(guess, nextGuess)) nextGuess else loop(nextGuess) } loop(firstGuess) } def sqrroot (x: Double) = fixedPointTail(averageDamp(y=>x/y))(1) sqrroot(2)

Non-Tail recursive version

def fixedPoint(f: Double => Double)(firstGuess: Double): Double ={ val nextGuess = f(firstGuess) if (isCloseEnough(firstGuess, nextGuess)) nextGuess else fixedPoint(f)(nextGuess) }