Math and Science with Python

Bisection Method in Python

Trap a root between two points and halve the interval until it is as small as you need.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • The sign-change rule f(a) * f(b) < 0
  • Halving the interval in a loop
  • How many steps a tolerance needs
x**3 - x - 2 on [1, 2]
  1. 1[1, 2]f(1) < 0, f(2) > 0
  2. 2[1.5, 2]f(1.5) < 0: keep the right half
  3. 3[1.5, 1.75]f(1.75) > 0: keep the left half
  4. 41.521380after 19 steps

Halve the interval every step

The problem

You know a root lies somewhere between 1 and 2, but there is no formula for it. Bisection is the first root-finding method most courses teach, because it is simple and it cannot fail once you have a sign change.

Think of it like this

Bisection is like guessing a number between 1 and 100 when someone tells you higher or lower. Each guess cuts the range in half, so after a few guesses you have narrowed it down to one number.

From a guessing game to code
a, b🔢 The range the number is in
mid = (a + b) / 2🎯 Guess the middle
f(a) * f(mid) <= 0↕️ Higher or lower? Keep that half
(b - a) / 2 > tol🔁 Keep guessing until the range is tiny
Keep the half that still contains the answer.
In one sentence

The bisection method finds a root of a continuous function on [a, b] where f(a) and f(b) have opposite signs, by repeatedly halving the interval and keeping the half where the sign changes.

Key points

  1. f(a) * f(b) > 0 means no sign change, so the function raises ValueError.
  2. Each step computes mid and keeps either [a, mid] or [mid, b].
  3. The interval halves every step, so tol=1e-6 takes 19 steps and tol=1e-12 takes 39.
  4. The answer is the middle of the final interval.

When should you use it?

  • Numerical methods exercises.
  • A safe fallback when faster methods fail.
  • Finding a starting interval for Newton's method.

When not to use it

  • You need many roots quickly: Newton's method or scipy.optimize.brentq converge much faster.
  • The function touches zero without changing sign, like x**2: bisection cannot find that root.

Example code

Open in editor →
main.py
def bisection(f, a, b, tol=1e-6):
    if f(a) * f(b) > 0:
        raise ValueError("f(a) and f(b) must have opposite signs")
    steps = 0
    while (b - a) / 2 > tol:
        mid = (a + b) / 2
        steps += 1
        if f(a) * f(mid) <= 0:   # the root is in the left half
            b = mid
        else:                    # the root is in the right half
            a = mid
    return (a + b) / 2, steps

# Root of x**3 - x - 2 between 1 and 2
f = lambda x: x**3 - x - 2
root, steps = bisection(f, 1, 2)
print(f"Root: {root:.6f} after {steps} steps")
print(f"f(root) = {f(root):.2e}")

# The same interval to a tighter tolerance needs more steps
root, steps = bisection(f, 1, 2, tol=1e-12)
print(f"Root: {root:.12f} after {steps} steps")

try:
    bisection(f, 2, 3)
except ValueError as error:
    print("Error:", error)
Get a Run button for this example

Result of running the code

Root: 1.521380 after 19 steps
f(root) = 4.27e-06
Root: 1.521379706805 after 39 steps
Error: f(a) and f(b) must have opposite signs

Code explanation

bisection() first checks that f(a) and f(b) have opposite signs; otherwise there may be no root in between, and it raises a ValueError, as the interval [2, 3] shows. Each loop finds mid and keeps the half where f changes sign. For x**3 - x - 2 on [1, 2] it reaches the root 1.521380 after 19 steps with tol=1e-6, and needs 39 steps for tol=1e-12, because every step halves the interval.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Not checking for a sign change

Without the check the loop still returns a number, but it is not a root.

Problem
def bisection(f, a, b, tol=1e-6):
    while (b - a) / 2 > tol:
Fix
def bisection(f, a, b, tol=1e-6):
    if f(a) * f(b) > 0:
        raise ValueError("no sign change")

Testing f(mid) == 0 to stop

With floats f(mid) is almost never exactly 0; stop on the interval width.

Problem
while f(mid) != 0:
Fix
while (b - a) / 2 > tol:

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson