Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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))
- }
- }
Add Comment
Please, Sign In to add comment