Advertisement
jules0707

fixedPoint

Feb 27th, 2017
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.08 KB | None | 0 0
  1. package example
  2. import math._
  3.  
  4. object week2Application {
  5.  
  6.   val tolerance = 0.0001                          //> tolerance  : Double = 1.0E-4
  7.  
  8.   def isCloseEnough(x: Double, y: Double) =
  9.     abs((x - y) / x) < tolerance                  //> isCloseEnough: (x: Double, y: Double)Boolean
  10.  
  11.   def fixedPoint(f: Double => Double)(firstGuess: Double) = {
  12.  
  13.     def iterate(guess: Double): Double = {
  14.       val next = f(guess)
  15.       if (isCloseEnough(guess, next)) next
  16.       else iterate(next)
  17.     }
  18.     iterate(firstGuess)
  19.   }                                               //> fixedPoint: (f: Double => Double)(firstGuess: Double)Double
  20.  
  21.   fixedPoint(x=>1+x/2)(1.0)                       //> res0: Double = 1.9998779296875
  22.  
  23.   def avgDamp(f:Double=>Double)(x:Double)=(f(x)+x)/2
  24.                                                   //> avgDamp: (f: Double => Double)(x: Double)Double
  25.  
  26.   def sqrt(x:Double):Double=
  27.   fixedPoint(avgDamp(y=>x/y))(1.0)                //> sqrt: (x: Double)Double
  28.  
  29.  sqrt(2)                                          //> res1: Double = 1.4142135623746899
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement