square root n by computing the next Xi term
<p>I am stuck on a problem from a textbook. It asks:</p>

<blockquote>
  <p>Write your own square root approximation function using the equation <code>Xk+1 = 1/2 * (Xk + n/(Xk)</code>, where <code>X0 = 1</code>.</p>
  
  <p>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.'</p>
</blockquote>

<p>I am using Python3.5.2 for this. </p>

<p><img src="http://i.stack.imgur.com/ujq7t.jpg" alt="attached a picture of the problem"> </p>

<p>Thanks!</p>

<p>A new school year, an old Babylonian method.</p>

<p>So, I won't solve this for you, but I can get you started.</p>

<p>We can write a little function that computes each <code>x_{k+1}</code>:</p>

<pre><code>def sqrt_step(n, xk):
    return 1/2.0 * (xk + float(n)/xk)
</code></pre>

<p>Let's set <code>n = 100</code>.</p>

<pre><code>sqrt_step(100, 1) # returns 50.5
</code></pre>

<p>Now let's feed that number into the function a few more times:</p>

<pre><code>sqrt_step(100, 50.5) # 26.2

sqrt_step(100, 26.2) # 15.0

sqrt_step(100, 15.0) # 10.8
</code></pre>

<p>...this converges to 10 as <code>k</code> goes to infinity.</p>

<p>Now, if only there was a way to perform an operation over and over again <code>k</code> times...I'm thinking of a three letter word that starts with 'f' and rhymes with 'ore'...</p>

<hr>

<h1>EDIT</h1>

<p>You've made an honest effort to solve the problem -- which I'm going to <em>assume</em> is a homework <em>practice exercise</em> and <strong>not</strong> an assignment. </p>

<p>You can solve this simply by using the <code>sqrt_step</code> function inside of a new function. This can be done as follows:</p>

<pre><code>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
</code></pre>

<p>Tests:</p>

<pre><code>square_root(64, 100)  # 8.0
square_root(144, 100) # 12.0
</code></pre>

<p>As you become more advanced, you will learn about functional programming techniques that allow you to avoid overwriting variables and explicitly writing <code>for</code> loops. For now however, this is the most straightforward approach.</p>

python square-root function-approximation