Chapter 4: Applied problem solving

Newton's Method for estimating square roots

face Josiah Wang

Many people have already developed efficient/accurate algorithms for estimating square roots.

In such cases, these algorithms are already defined. So instead of coming up with an algorithm, our “Step 2” of programming is now replaced with “understand the algorithm”.

Now, here is an exercise for you to implement an existing algorithm.

You will now try to estimate the square root of a number n (as entered by the user), using Newton’s method.

In Newton’s Method (or Newton–Raphson method), you start with any estimate of the square root, x.

You then compute a new estimate for x using the equation x^{new}=\frac{x+\frac{n}{x}}{2}.

You then update x with the new estimate x^{new}, and repeat the process until x and x^{new} do not change (or that the difference is “close enough”). Then x will be your estimate!

Now that you are given this recipe, can you implement it in Python? Make sure that you understand the recipe first, and once you are comfortable, start cooking! 🍳

You do not have to strictly ‘translate’ the equation directly to code. You are allowed to ‘rephrase’ the equation or adapt the steps if it makes your code more readable or efficient, as long as the output is equivalent.

It will also be useful to print out the x at each step, so that you can observe for yourself how the algorithm tries to estimate the square root.

Remember to test/debug as you code!

I will reveal my solutions in the next chapter (for reasons that will become clear). Please do not peek at the solution just yet!