How to do the Bisection method in Python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The bisection method is one of the safest ways to find a root of a continuous function numerically. It is slower than Newton's method, but it is much easier to reason about because it only needs a sign change over an interval and repeatedly halves that interval until the root is isolated to the desired tolerance.
The Core Idea
If a continuous function has opposite signs at two endpoints a and b, then there is at least one root somewhere between them. The bisection method repeatedly computes the midpoint and keeps the half-interval that still contains a sign change.
The algorithm is:
- choose
aandbsuch thatf(a)andf(b)have opposite signs - compute midpoint
c = (a + b) / 2 - decide whether the root is in
[a, c]or[c, b] - repeat until the interval is small enough or
f(c)is close enough to zero
This makes the method robust and predictable.
A Basic Python Implementation
Here is a simple implementation with error checks and a stopping tolerance.
This version is enough for many small scientific and educational tasks.
Example: Solve x^3 - x - 2 = 0
Now apply the function to a concrete example.
The interval [1, 2] works because f(1) = -2 and f(2) = 4, so the function changes sign across the interval.
Track Iterations for Debugging or Teaching
For learning or debugging, it is useful to record each midpoint and interval update.
Seeing the interval shrink makes the convergence behavior much easier to understand.
Choose a Sensible Stopping Rule
There are two common stopping rules:
- the function value at the midpoint is close enough to zero
- the interval width is smaller than the required tolerance
Using both is common because some functions flatten near the root, and in that case interval width is a more reliable indicator than the function value alone.
Common Pitfalls
- Choosing an interval where
f(a)andf(b)have the same sign. - Applying the method to a discontinuous function and assuming the sign test still guarantees a root.
- Using an interval so large that convergence takes more iterations than expected.
- Forgetting to stop when the interval width is sufficiently small.
- Expecting bisection to be fast when the real advantage is robustness, not speed.
Summary
- The bisection method finds a root by repeatedly halving an interval with a sign change.
- It needs a continuous function and endpoints with opposite signs.
- A small Python implementation is enough for many practical tasks.
- The method is reliable and easy to debug, even if it is not the fastest root finder.
- Use both function-value and interval-width stopping rules for better numerical behavior.

