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.
This file contains 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
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)) | |
} | |
} |
No comments:
Post a Comment