Created
September 14, 2011 21:16
-
-
Save cgopalan/1217811 to your computer and use it in GitHub Desktop.
Scala Cube Root
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
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