Last active
August 29, 2015 14:14
-
-
Save Kornel/4453a706981bd1b46387 to your computer and use it in GitHub Desktop.
Square root calculated using the Newton - Raphson method using infinite Streams in Scala
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
import scala.annotation.tailrec | |
object NewtonRaphsonSquareRoot extends App { | |
@tailrec | |
def within(epsilon: Double, s: Stream[Double]): Double = s match { | |
case x0 #:: x1 #:: xs => if (math.abs(x0 - x1) < epsilon) x1 else within(epsilon, x1 #:: xs) | |
} | |
def sqrt(n: Double)(implicit epsilon: Double): Double = { | |
require(n >= 0) | |
def next(x0: Double) = (x0 + n / x0) / 2 | |
val initial = n / 2 | |
within(epsilon, Stream.iterate(initial)(next)) | |
} | |
implicit val epsilon = 0.1 | |
println(sqrt(64)) | |
println(sqrt(16)) | |
println(sqrt(416025)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment