Guest User

Untitled

a guest
Jan 21st, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. object FixedPoint {
  2. var tolerance = 0.0001
  3. def abs(x: Double) = if (x >= 0) x else -x
  4. def isCloseEnough(x: Double, y: Double) = abs((x - y) / x) < tolerance
  5. def fixedPoint(f: Double => Double)(firstGuess: Double) = {
  6. def iterate(guess: Double): Double = {
  7. val next = f(guess)
  8. println(next)
  9. if (isCloseEnough(guess, next)) next
  10. else iterate(next)
  11. }
  12. iterate(firstGuess)
  13. }
  14. def averageDamp(f: Double => Double)(x: Double) = (x + f(x)) / 2
  15. def cbrt(x: Double) = fixedPoint(averageDamp(y => x/math.pow(y,2)))(1.0)
  16.  
  17. def main(args: Array[String]) {
  18. println("calculating cube root of 2 : " + cbrt(2))
  19. println("calculating cube root of 8 : " + cbrt(8))
  20. }
  21. }
Add Comment
Please, Sign In to add comment