Newton’s method is a powerful technique for numerically computing the zeros of differentiable functions. It is an iterative technique, meaning that instead of applying a formula to directly compute the answer, it repeatedly tries to compute a better approximation until the desired accuracy is reached. Iteration is just a fancy word for repetition, which we know how to do in Python using for loops and while loops.
Newton’s method gives a surprisingly simple algorithm for computing .
Listing 8.2: Newton’s Method (Algorithm)
# To compute sqrt(k)
Begin with an initial guess x.
Repeat until desired accuracy is reached:
Replace x with the average of x and k/x.
That’s all there is to it. At the end of the loop, x will be approximately equal To .
This is an algorithm in pseudocode, but it isn’t yet an executable program. Your task will be to convert this algorithm into a working Python program.
Here are some new bits of Python that may be helpful:
Scientific notation Floats may be specified in Python with an “e” before the exponent. For example, 2.914e6 represents .
Absolute value Python provides the built-in function:
abs(x) |
Absolute value of x. |
The reason absolute value is useful is that it gives an easy measure of how close together two numbers are: the distance between x and y is |x − y|.
One last piece of advice that addresses a question you may have already thought of. How is it possible to know how close x is to without knowing the value of ahead of time? In other words, how do we know when we are close enough? The answer is to compare x2 with k instead of x to . This will not tell you how close x is to the actual root, but it gives you some measurement of accuracy.
18.188.65.241