Skip to content

Instantly share code, notes, and snippets.

@RyanSusana
Created May 29, 2020 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanSusana/770515a082b7238344facff2b950d170 to your computer and use it in GitHub Desktop.
Save RyanSusana/770515a082b7238344facff2b950d170 to your computer and use it in GitHub Desktop.
def sqrt(x: Double): Double = {
def abs(x: Double) = if (x > 0) x else -x
def isGood(guess: Double, x: Double): Boolean =
abs(guess * guess - x) < 0.0001
def improve(guess: Double, x: Double) =
(guess + x / guess) / 2
def sqrtIter(x: Double, guess: Double): Double =
if (isGood(guess, x)) guess else sqrtIter(improve(guess, x), x)
sqrtIter(x, 1.0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment