10.1. Repeating Calculations

While calculating an approximate square root with Newton’s method, we often want to use the formula \(1/2((N/G) + G)\) multiple times to keep improving our approximation. Earlier, we defined a procedure to make it easier to reuse the formula. But if we want to apply the formula a whole bunch of times in a row, a loop makes sense. Try running this program with the Codelens:

Each time we pass through the loop, we update the guess and it becomes a little closer to the truest value for the square root we can represent (we can never write a perfect representation of the answer as a decimal, so we have to settle for being correct to a significant number of digits). The for loop is initially set to repeat 4 times, which gets us pretty close to the true value of the square root - 10.48808848170152.

The number of repetitions needed to get the most accurate possible square root for a given number is not always the same. If you change number to be 2, it would only take 5 iterations of the loop to find the best possible guess for the square root. Without experimenting, we don’t really know how many repetitions are needed to get the best possible answer. Currently our program says something like “repeat this calculation 5 times”. What we would like to say is something more like “repeat this calculation while it keeps producing a new value”.

You have attempted of activities on this page