Last active
October 15, 2015 18:58
-
-
Save miguel-vila/90029b16c167b974592b to your computer and use it in GitHub Desktop.
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
// 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 |
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
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