Skip to content

Instantly share code, notes, and snippets.

@cgopalan
Created September 14, 2011 21:16
Show Gist options
  • Save cgopalan/1217811 to your computer and use it in GitHub Desktop.
Save cgopalan/1217811 to your computer and use it in GitHub Desktop.
Scala Cube Root
object FixedPoint {
var tolerance = 0.0001
def abs(x: Double) = if (x >= 0) x else -x
def isCloseEnough(x: Double, y: Double) = abs((x - y) / x) < tolerance
def fixedPoint(f: Double => Double)(firstGuess: Double) = {
def iterate(guess: Double): Double = {
val next = f(guess)
println(next)
if (isCloseEnough(guess, next)) next
else iterate(next)
}
iterate(firstGuess)
}
def averageDamp(f: Double => Double)(x: Double) = (x + f(x)) / 2
def cbrt(x: Double) = fixedPoint(averageDamp(y => x/math.pow(y,2)))(1.0)
def main(args: Array[String]) {
println("calculating cube root of 2 : " + cbrt(2))
println("calculating cube root of 8 : " + cbrt(8))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment