Problem 26
Question
Maybe you have tried to hit the square root key on a calculator multiple times and then squared the number again an equal number of times. These set of inverse mathematical operations should of course bring you back to the starting value for the computations, but this does not always happen. To avoid tedious pressing of calculator keys we can let a computer automate the process. Here is an appropriate program: from math import sqrt for n in range(1, 60): r = 2.0 for i in range(n): r = sqrt(r) for i in range(n): r = r**2 print ’%d times sqrt and **2: %.16f’ % (n, r) Explain with words what the program does. Then run the program. Round-off errors are here completely destroying the calculations when \(\mathrm{n}\) is large enough! Investigate the case when we come back to 1 instead of 2 by fixing the \(\mathrm{n}\) value and printing out \(\mathrm{r}\) in both for loops over i. Can you now explain why we come back to 1 and not 2 ? Name of program file: repeated_sqrt.py.
Step-by-Step Solution
VerifiedKey Concepts
Round-off Errors
Why do round-off errors matter? Over multiple iterations, especially in problems involving many operations, these errors grow. Taking repeated square roots and subsequently squaring them in a loop (as shown in the exercise) is a perfect situation to observe their effect. Ideally, repeatedly finding the square root and then squaring the same number should yield the initial number. However, due to round-off errors, the outcome diverges from expectations. When 'n' becomes large, round-off errors become significantly impactful, causing divergences like obtaining 1 instead of 2.
Debugging Programs with Print Statements
In the context of the exercise, modifying the program to print the value of 'r' within both loops sheds light on the round-off errors' effect at each step. By examining these intermediate values, you can see how 'r' gradually diverges from its expected path. Print statements are a straightforward yet powerful debugging tool, often used by programmers to track variable states or logic flow, especially when dealing with complex operations like floating-point arithmetic.
Fixed Points in Numerical Operations
This behavior is apparent in the exercise when repeated square root and squaring operations cause 'r' to stabilize at 1 instead of 2. Initially, minor deviations might just seem like minor errors. But, over many cycles, they compound until the result drifts towards the fixed point, which is 1 in this case. Recognizing fixed points helps explain why values converge and provides insight into the limitations of numerical methods, especially when using iteration and floating-point calculations together.