Skip to content

Instantly share code, notes, and snippets.

@miguel-vila
Last active October 15, 2015 18:58
Show Gist options
  • Save miguel-vila/90029b16c167b974592b to your computer and use it in GitHub Desktop.
Save miguel-vila/90029b16c167b974592b to your computer and use it in GitHub Desktop.
// a #:: f(a) #:: f(f(a)) #:: f(f(f(a))) #:: ...
def repeat[A](f: A => A)(a: => A): Stream[A] = a #:: repeat(f)(f(a))
def next(n: Double)(x: Double): Double = (x + n/x)/2.0
def within(eps: Double)(s: Stream[Double]): Double = s match {
case a #:: b #:: rest => if(Math.abs(a-b)<=eps) b else within(eps)(rest)
case _ => throw new Exception("El stream debería tener por lo menos dos elementos")
}
def sqrt(a0: Double, eps: Double, n: Double): Double = within(eps)(repeat(next(n))(a0))
sqrt(2,0.000001,9) // 3.0
def sqrt(a0: Double, eps: Double, n: Double): Double = {
var x = a0
var y = a0 + 2.0 * eps
while ( Math.abs(x-y) > eps ) {
y = x
x = (x + n/x) / 2.0
}
x
}
sqrt(2,0.000001,9) // 3.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment