Lesson goal: Find a square root by interation

Previous: Interating the logistic function | Home | Next: A clever for-loop for Pi

In a past lesson you used a for-loop to iterate a function over and over again. In that case, you looked for a given pattern to emerge. Here's a nifty iteration that will end up giving you the square root of a number (see Cheney, et. al., 5th ed, p. 117).

Suppose you want to find the square root of a number in the variable $R$, and you start with a guess in varable $x$. Perhaps $x$ can start at $R/2$ (since you know the square root of a number is always less than the number itself). We'll call this initial $x$, $x_0$. You can find a still better approximation to $\sqrt{R}$ by finding the next $x$, or $x_1$ by: $$x_1=\frac{1}{2}(x_0+\frac{R}{x_0})$$ In general, the iteration to find $\sqrt{R}$ is given by $$x_{n+1}=\frac{1}{2}(x_n+\frac{R}{x_n})$$

In this lesson, try to practice your for-loops and programming formulas into the computer by writing some code to find $\sqrt{R}$.

Now you try. Fix the R= line, the for-loop, and the key interation formula in the x= line.

Type your code here:


See your results here:

This code will not run! You have to fix the R= line. Set this equal to the number you wish to take the square root of. Then, fix the for-loop to interate some number of times...10? 50? 100? Lastly, program in the formula for the new x in the x= line, from the current $x$ that exists as this line is executed by the computer.

Note that the use of the assignment operator = is quite clear here, as introducted in a past lesson. We are suggesting that you use x on both sides of the = sign. Is this OK? Dismiss.

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.