To compute the square root of a number, x, we first need to make an initial estimate, y, let’s say 1. We improve the estimate by taking the average of y and x/y.
Let’s look at an example. The table below shows how Newtons method would compute the square root of 4 by approximation.
svg viewer
If we continue the above calculations, the average would eventually converge to 2.
Brace yourself because below, you’ll be introduced to your first extensive Scala program!
Implementation in Scala
To implement the above method in Scala, we need to define five functions interdependent with each other.
abs(): will return the absolute value of a given number
isGoodEnough(): will let us know if the average is close enough to the actual value
improve(): will return the average of y and x/y
sqrtIter(): a recursive function which will compute each iteration of Newton’s method
sqrt(): Will use the sqrtIter() function and return the square root of the given number
When defining a function dependent on other functions, make sure to define them above the dependent function.