gl/ripetizioni

Newton's method and bisection in Python

The bisection and Newton-Raphson methods for finding the zeros of a function, with complete Python code, stopping criteria and a comparison of convergence.

by Gaetano Livornese

Read the original in Italian

If you are in Year 5 of the applied sciences liceo (the Italian academic high school with a science and computing focus), in the first term computer science reaches numerical methods: finding the zeros of a function with the computer, when the equation cannot be solved with a formula. The written test or lab assignment on this block usually falls six to nine weeks from now, between late November and December. There is time, and the topic is one of the best in the programme, because for the first time the code you write gives a result you can check with a calculator.

Every year in my lessons I see the same two obstacles: understanding why the method converges, and writing a loop with a sensible stopping criterion. I always use the same example, the simplest there is: , whose positive root is . We already know the answer, so we can see whether the method finds it.

If Python is still a bit new to you, start from programming in Python from scratch. To think about loops and conditions before the code, you need flowcharts and pseudocode. For another example of an algorithm with a cost comparison, see sorting algorithms.

The bisection method

The idea comes from the intermediate value theorem: if is continuous on and and have opposite signs, there is at least one root in the interval. You take the midpoint and keep the half where the sign changes. Repeat.

For on : and , opposite signs, so we can start.

Stepabmf(m)
1121.50.25
211.51.25-0.4375
31.251.51.375-0.109375
41.3751.51.43750.0664
51.3751.43751.40625-0.0225

After 5 steps the root lies in : the maximum error is . At every step the interval halves, so after steps the width is . To get an error below from an interval of width 1 you need , that is (indeed ).

The Newton–Raphson method

Newton’s method uses the derivative: from the point you draw the tangent to the graph and take the point where it meets the -axis. The formula is:

For the derivative is , and the formula becomes . Let us start from :

After only 3 steps there are 11 correct digits. A useful observation for the test: the number of correct digits roughly doubles at every step (error: about , then , then ). Bisection, by contrast, gains just one bit (a factor of 2) per step.

The Python code

I tested these functions with python3 on the example above.

def f(x):
    return x * x - 2

def df(x):
    return 2 * x

def bisection(f, a, b, tol=1e-6, max_iter=100):
    if f(a) * f(b) > 0:
        raise ValueError("f(a) and f(b) must have opposite signs")
    for i in range(1, max_iter + 1):
        m = (a + b) / 2
        if f(m) == 0 or (b - a) / 2 < tol:
            return m, i
        if f(a) * f(m) < 0:
            b = m
        else:
            a = m
    return (a + b) / 2, max_iter

def newton(f, df, x0, tol=1e-10, max_iter=50):
    x = x0
    for i in range(1, max_iter + 1):
        d = df(x)
        if d == 0:
            raise ZeroDivisionError("zero derivative")
        x_new = x - f(x) / d
        if abs(x_new - x) < tol:
            return x_new, i
        x = x_new
    return x, max_iter

print(bisection(f, 1, 2))
print(newton(f, df, 1.5))

Output: bisection gives about 1.4142141 in 20 iterations, Newton 1.4142135623730951 in 4 iterations. With a tolerance of bisection needs 34. For the same precision, Newton does less than 15% of the work.

A few choices you should be able to explain in the lab:

  • the functions receive f as a parameter, so the same code works for any equation;
  • max_iter avoids an infinite loop if the method does not converge;
  • the initial sign check in bisection protects against intervals that do not contain a root;
  • in newton the d == 0 check avoids division by zero.

Stopping criteria

A numerical loop must know when to stop. There are three criteria, often combined:

  1. Width of the interval (bisection): .
  2. Difference between approximations: .
  3. Residual: . Careful: if the function is very flat near the root, a small residual does not guarantee an close to the root.

Always add a maximum number of iterations: it is the last safety net.

Comparison and limits

BisectionNewton
NeedsAn interval with a sign changeThe derivative and a starting point
ConvergenceAlways, but slow (one bit per step)Very fast, if it starts close
RisksFewZero derivative, distant starting point, divergence
Cost per stepOne evaluation of and

In practice: Newton is faster, bisection is more robust. A typical mistake is to start Newton from for . The derivative is 0 and the code raises the exception. With the first step sends the point to , and more steps are needed to get back near the root: the method works, but the starting point matters.

If you want a level beyond high school, where error and convergence are also studied formally, you will find it in numerical methods for the exam. For the calculus behind Newton’s method, it is worth revising derivatives explained well.

A complete exercise

Find as the positive root of , using Newton from . The derivative is and the step is .

The exact value is : at the third step the error is already below . How many iterations would bisection have used on for the same tolerance? You need , that is (). The comparison 3 against 27 is the answer many teachers want to hear about the speed of convergence.

A warning about the code: if you are asked to modify it for , only f and df change, not the two method functions. If you had to touch bisection or newton, something is not general.

Test yourself

Before a test, redo by hand three iterations of Newton for from and then check with the code. Then try the free practice test on high school tests. If you want to go over your lab code together, we can do it in the free 30-minute introductory call with me.

Frequently asked questions

How many iterations does bisection need to get an error below 10^-6?

It needs 20 iterations starting from an interval of width 1, because the width halves at every step and 2^20 is more than a million.

When does Newton's method fail?

When the derivative is zero near the starting point, or when the starting point is too far from the root: the method can leave the interval or fail to converge.

Why does bisection require f(a) and f(b) to have opposite signs?

By the intermediate value theorem, if the function is continuous and changes sign at the endpoints, there is at least one root inside the interval.

Which stopping criterion should I use in Newton's method?

Stop when the difference between two successive approximations is smaller than a tolerance, and always set a maximum number of iterations.

Keep reading

Want to put what you read into practice?

Let's talk for 30 minutes, free: we look together at where you are stuck and I tell you honestly how I can help.

Or message me on WhatsApp.