Babeeshka - 4 months ago 23

Python Question

I am stuck on a problem from a textbook. It asks:

Write your own square root approximation function using the equation, where`Xk+1 = 1/2 * (Xk + n/(Xk)`

.`X0 = 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. I attached a picture of the problem too because I'm not sure how to write the equation in this formatting block.

Thanks!

Answer

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'...