fixedPoint: (f: Double => Double)(firstGuess: Double)Double
The task here is to find fixed points of functions and the application of the task will be to our well known square root with Newton's method
Square Root by Newton's method:
Calculates the square root of parameter x
def sqrt(x: Double): Double = ...
The classical way to achieve this is by successive approximations using Newton’s method.
To compute sqrt(x):
- Start with an initial estimate y (let’s pick y = 1).
- Repeatedly improve the estimate by taking the mean of y and x/y.
Example: x=2
Estimation Quotient Mean
1 2/1=2 1.5
1.5 2/1.5=1.333 1.4167
1.4167 2/1.4167=1.4118 1.4142
1.4142 so on
First, define a function which computes one iteration step
def sqrtIter(guess: Double, x: Double): Double =
if (isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)
Second, define a function improve to improve an estimate and a test to check for terminatation:
def improve(guess: Double, x: Double) =
(guess + x / guess) / 2
def isGoodEnough(guess: Double, x: Double) =
abs(guess * guess - x) < 0.001
Third, define the sqrt function:
def sqrt(x: Double) = srqtIter(1.0, x)
using your Fixedpoint function we also calculating square root of a number
first see what is fixed point:
A number x
is called a fixed point of a function f if f(x) = x
For some functions f we can locate the fixed points by starting with an initial estimate and then by applying f in a repetitive way.
x, f(x), f(f(x))
This leads to the following function for finding a fixed point:
val tolerance = 0.0001
def isCloseEnough(x: Double, y: Double) =
abs((x - y) / x) / x < tolerance
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)
}
In this formulation,fixedPoint
is a function which returns another function, namely the specialized function iterate
here fixedPoint
def fixedPoint(f: Double => Double)(firstGuess: Double)
the function fixedPoint
is applied to the function f: Double => Double
. The resulting
function is then applied to the second argument
(firstGuess: Double)
This notation is possible because function application associates to the left. That is,
if args1 and args2 are argument lists, then f(args1)(args2)
is equivalent to (f(args1))args2
In your program first argument is function that take input type is Double and return type is Double and then apply this function to the guess
reformulation of the square root function.
Let’s start with a specification of sqrt:
sqrt(x) = the y such that y*y = x
= the y such that y = x / y
Hence, sqrt(x) is a fixed point of the function y => x / y
. This suggests that
sqrt(x)
can be computed by fixed point iteration:
def sqrt(x: double) = fixedPoint(y => x / y)(1.0)
this is a long answer but i think it will help you to understand the concept