Skip to content

Instantly share code, notes, and snippets.

@rbobillot
Last active August 29, 2015 14:20
Show Gist options
  • Save rbobillot/b0bc8e377c8626f8f9a4 to your computer and use it in GitHub Desktop.
Save rbobillot/b0bc8e377c8626f8f9a4 to your computer and use it in GitHub Desktop.
val tolerance = 0.0001
def isCloseEnough( x: Double, y: Double ) = Math.abs( (x - y) / x ) < tolerance
def fixedPoint( f: Double => Double )( first: Double ) = {
def iterate(guess: Double): Double = {
val next = f(guess)
if (isCloseEnough( guess, next ))
next
else
iterate( next )
}
iterate( first )
}
def sqrt( x: Double ) = fixedPoint(y => ( y + x/y) / 2 )( 1.0 )
println( sqrt(9876543) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment