Advertisement
jules0707

sqrt

Feb 27th, 2017
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.65 KB | None | 0 0
  1. package week1
  2.  
  3. import java.lang.Math._
  4.  
  5. object session {
  6.  
  7.   def sqrt(x: Double) = {
  8.     def sqrtItr(guess: Double, x:Double): Double =
  9.       if (isGoodEnough(guess)) guess
  10.       else (sqrtItr(improve(guess),x))
  11.  
  12.     def isGoodEnough(guess: Double) =
  13.       abs(guess * guess - x) / x < 0.0001
  14.  
  15.     def improve(guess: Double) =
  16.       (guess + x / guess) / 2
  17.  
  18.     sqrtItr(1.0, x)
  19.   }                                               //> sqrt: (x: Double)Double
  20.  
  21.   sqrt(1e-6)                                      //> res0: Double = 0.0010000001533016628
  22.   sqrt(1e60)                                      //> res1: Double = 1.0000000031080746E30
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement