Skip to content

Instantly share code, notes, and snippets.

@bjarkevad
Last active December 25, 2015 12:59
Show Gist options
  • Save bjarkevad/6980191 to your computer and use it in GitHub Desktop.
Save bjarkevad/6980191 to your computer and use it in GitHub Desktop.
Scala stuff
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