Skip to content

Instantly share code, notes, and snippets.

@RafalSladek
Last active July 26, 2016 17:54
Show Gist options
  • Select an option

  • Save RafalSladek/e929fa51a231d34fe1fffdd9b25083d4 to your computer and use it in GitHub Desktop.

Select an option

Save RafalSladek/e929fa51a231d34fe1fffdd9b25083d4 to your computer and use it in GitHub Desktop.
import math.abs
val tolerance = 0.0001
def isCloseEnough(x: Double, y: Double) =
abs((x - y) / x) / x < tolerance
def fixedPoint(f: Double => Double)(firstGuess: Double) = {
def iterate(guess: Double): Double = {
val next = f(guess)
if (isCloseEnough(guess, next)) next
else iterate(next)
}
iterate(firstGuess)
}
fixedPoint(x => 1 + x / 2)(1)
// avaraging successive values
def avarageDamp(f: Double => Double)(x: Double) = (x + f(x)) / 2
def sqrt(x: Double) = fixedPoint(avarageDamp(y => x / y))(1.0)
sqrt(2)
@RafalSladek
Copy link
Copy Markdown
Author

you can express sqrt as fixedpoint function
y*y =>x -> y => x/y
but we need smaller steps so we y => (y + x/y) / 2

@RafalSladek
Copy link
Copy Markdown
Author

avaraging successive values will be extracted to a separate function avarageDamp which modifies input function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment