Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package example
- import math._
- object week2Application {
- val tolerance = 0.0001 //> tolerance : Double = 1.0E-4
- def isCloseEnough(x: Double, y: Double) =
- abs((x - y) / x) < tolerance //> isCloseEnough: (x: Double, y: Double)Boolean
- def fixedPoint(f: Double => Double)(firstGuess: Double) = {
- def iterate(guess: Double): Double = {
- val next = f(guess)
- if (isCloseEnough(guess, next)) next
- else iterate(next)
- }
- iterate(firstGuess)
- } //> fixedPoint: (f: Double => Double)(firstGuess: Double)Double
- fixedPoint(x=>1+x/2)(1.0) //> res0: Double = 1.9998779296875
- def avgDamp(f:Double=>Double)(x:Double)=(f(x)+x)/2
- //> avgDamp: (f: Double => Double)(x: Double)Double
- def sqrt(x:Double):Double=
- fixedPoint(avgDamp(y=>x/y))(1.0) //> sqrt: (x: Double)Double
- sqrt(2) //> res1: Double = 1.4142135623746899
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement