Wednesday, September 14, 2011

Scala By Example Chapter 5 Solutions - Exercise 5.3.1

Exercise 5.3.1 Write a function for cube roots using fixedPoint and averageDamp.

Both fixedPoint and averageDamp functions remain the same. Instead of sqrt, now theres a cbrt function which calculates the cube root. The math library is used to avail of the exponential function.

object FixedPoint {
var tolerance = 0.0001
def abs(x: Double) = if (x >= 0) x else -x
def isCloseEnough(x: Double, y: Double) = abs((x - y) / x) < tolerance
def fixedPoint(f: Double => Double)(firstGuess: Double) = {
def iterate(guess: Double): Double = {
val next = f(guess)
println(next)
if (isCloseEnough(guess, next)) next
else iterate(next)
}
iterate(firstGuess)
}
def averageDamp(f: Double => Double)(x: Double) = (x + f(x)) / 2
def cbrt(x: Double) = fixedPoint(averageDamp(y => x/math.pow(y,2)))(1.0)
def main(args: Array[String]) {
println("calculating cube root of 2 : " + cbrt(2))
println("calculating cube root of 8 : " + cbrt(8))
}
}
view raw cuberoot.scala hosted with ❤ by GitHub

No comments: