Last active
December 25, 2015 12:59
-
-
Save bjarkevad/6980191 to your computer and use it in GitHub Desktop.
Scala stuff
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
import scala.annotation.tailrec | |
import math.abs | |
//Fixed point algorithm | |
object fpalgorithm { | |
val tolerance = 0.0001 | |
def fixedPoint(f: Double => Double)(firstGuess: Double) = { | |
def isCloseEnough(x: Double, y: Double) = | |
abs((x - y) / x) / x < tolerance | |
@tailrec | |
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 | |
//With averageDamp | |
def sqrt(x: Double) = { | |
fixedPoint(averageDamp(y => x / y))(1.0) | |
} | |
//Without averageDamp | |
def sqrt2(x: Double) = fixedPoint(y => (y + (x / y)) / 2)(1.0) | |
sqrt(512) * sqrt(512) | |
sqrt2(512) * sqrt2(512) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment