Created
October 16, 2019 12:59
-
-
Save ahafidi/5106e2cf16fa3dcca4fed660e4bf3a51 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
| val tolerance = 0.00001 | |
| def isCloseEnough(x: Double, y: Double): Boolean = | |
| Math.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) | |
| } | |
| def averageDamp(f: Double => Double)(x: Double) = (x + f(x)) / 2 | |
| def my_sqrt(x: Double) = fixedPoint(averageDamp(y => x / y))(1.0) | |
| Math.sqrt(2) | |
| my_sqrt(2) | |
| Math.sqrt(3) | |
| my_sqrt(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment