I am stuck on a problem from a textbook. It asks:
Write your own square root approximation function using the equation
Xk+1 = 1/2 * (Xk + n/(Xk)
, whereX0 = 1
.This equation says that the sqrt'n' can be found by repeatedly computing the next Xi term. The larger number of terms used, the better the answer. Allow your function to have two input parameters, the number that you want the square root of and the number of terms to compute.'
I am using Python3.5.2 for this.
Thanks!
A new school year, an old Babylonian method.
So, I won't solve this for you, but I can get you started.
We can write a little function that computes each x_{k+1}
:
def sqrt_step(n, xk):
return 1/2.0 * (xk + float(n)/xk)
Let's set n = 100
.
sqrt_step(100, 1) # returns 50.5
Now let's feed that number into the function a few more times:
sqrt_step(100, 50.5) # 26.2
sqrt_step(100, 26.2) # 15.0
sqrt_step(100, 15.0) # 10.8
...this converges to 10 as k
goes to infinity.
Now, if only there was a way to perform an operation over and over again k
times...I'm thinking of a three letter word that starts with 'f' and rhymes with 'ore'...
You've made an honest effort to solve the problem -- which I'm going to assume is a homework practice exercise and not an assignment.
You can solve this simply by using the sqrt_step
function inside of a new function. This can be done as follows:
def square_root(n, k):
xk = 1
for i in range(k):
xk = sqrt_step(n, xk) # or just: xk = 1/2.0 * (xk + float(n)/xk)
return xk
Tests:
square_root(64, 100) # 8.0
square_root(144, 100) # 12.0
As you become more advanced, you will learn about functional programming techniques that allow you to avoid overwriting variables and explicitly writing for
loops. For now however, this is the most straightforward approach.