This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Breaking the flow

Newton's method (solutions)

face Josiah Wang

Here are some example solutions for Newton’s method for estimating square roots.

This first solution is a more literal implementation of the given algorithm. I have chosen semantically meaningful variables such as guess and old_guess. I also used (guess + n/guess) * 0.5 instead of (guess + n/guess) / 2 just to show that there are different ways to implement an equation.

n = float(input("Please enter a positive number: "))
guess = n
epsilon = 0.0000001
found = False

while not found:
    old_guess = guess
    guess = (guess + n/guess) * 0.5
    if abs(guess - old_guess) < epsilon:
        found = True
        print(guess)

This second solution uses a while True loop, but with a break statement to exit the loop. I think both are acceptable, although I personally find the first version just very slightly easier to understand than while True.

n = float(input("Please enter a positive number: "))
guess = n
epsilon = 0.0000001

while True:
    old_guess = guess
    guess = (guess + n/guess) * 0.5
    if abs(guess - old_guess) < epsilon:
        print(guess)
        break

This third solution is a very compact implementation that does not directly translate the given algorithm, but instead interprets it in a different way. Rather than checking whether the old guess and the new guess are close enough, it instead directly checks whether squaring guess gets you close enough to n. So, this implementation can also be seen as an improvement to the exhaustive search algorithm, but with a smarter way of selecting the candidate solutions. The result is a more concise yet still readable piece of code. No break is needed either!

n = float(input("Please enter a positive number: "))
guess = n - 1
epsilon = 0.0000001

while abs(guess*guess - n) > epsilon:
    guess = (guess + n/guess) * 0.5

print(guess)

Also, whenever you find yourself needing to use break, try to think of whether it is really necessary? Can you ‘rephrase’ your algorithm so that it is even more readable and does not need to use break? In general, use break only when it makes your code more readable.

The main lesson is that there are many ways to implement a solution to the same algorithm. Some are more compact or efficient than others. The most important thing, however, is to ensure that your code works correctly. Otherwise, there is no point is having an elegant, short, or efficient piece of code.