Last active
July 26, 2016 17:54
-
-
Save RafalSladek/e929fa51a231d34fe1fffdd9b25083d4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import math.abs | |
| val tolerance = 0.0001 | |
| def isCloseEnough(x: Double, y: Double) = | |
| abs((x - y) / x) / x < tolerance | |
| def fixedPoint(f: Double => Double)(firstGuess: Double) = { | |
| def iterate(guess: Double): Double = { | |
| val next = f(guess) | |
| if (isCloseEnough(guess, next)) next | |
| else iterate(next) | |
| } | |
| iterate(firstGuess) | |
| } | |
| fixedPoint(x => 1 + x / 2)(1) | |
| // avaraging successive values | |
| def avarageDamp(f: Double => Double)(x: Double) = (x + f(x)) / 2 | |
| def sqrt(x: Double) = fixedPoint(avarageDamp(y => x / y))(1.0) | |
| sqrt(2) |
Author
Author
avaraging successive values will be extracted to a separate function avarageDamp which modifies input function
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you can express sqrt as fixedpoint function
y*y =>x -> y => x/y
but we need smaller steps so we y => (y + x/y) / 2