Bisection Method Code in Python (With Examples)

13 hours ago 6
Club.noww.in

The bisection method code in Python finds a root of f(x) by halving an interval [a, b] where the function changes sign, keeping the half that still contains the root, until the interval is tiny:

mid = (a + b) / 2 if f(a) * f(mid) < 0: b = mid # root on the left else: a = mid # root on the right

I ran each example with Python 3.12.5 and SciPy 1.18.1, and I checked my own function against SciPy’s built-in solver.

We’ll write a reusable function, watch the interval shrink in a table, handle bad intervals, compare with SciPy, solve a real car loan rate, and plot the convergence.

Bisection method code in Python (reusable function)

The function needs a sign change between a and b, a tolerance to stop at, and a maximum number of iterations as a safety net:

def bisection(f, a, b, tol=1e-6, max_iter=100): fa, fb = f(a), f(b) if fa * fb > 0: raise ValueError(f"f(a) and f(b) must have opposite signs (got {fa:.3f} and {fb:.3f})") for i in range(1, max_iter + 1): mid = (a + b) / 2 fm = f(mid) if fm == 0 or (b - a) / 2 < tol: return mid, i if fa * fm < 0: # root is in the left half b, fb = mid, fm else: # root is in the right half a, fa = mid, fm raise RuntimeError("did not converge") f = lambda x: x**3 - x - 2 root, steps = bisection(f, 1, 2) print(f"root = {root:.6f} after {steps} iterations") print(f"f(root) = {f(root):.2e}")

Output:

root = 1.521380 after 20 iterations f(root) = 4.27e-06
Command Prompt output of a Python bisection method function finding the root of x cubed minus x minus 2The root of x³ − x − 2 is about 1.521380, found in 20 iterations.

Each iteration halves the interval, so starting with a width of 1, about 20 halvings get the error below one millionth. That predictability is bisection’s big selling point.

Watch the interval shrink: an iteration table

Printing each step shows exactly how it works. The error bound halves every row, no matter what the function looks like:

from tabulate import tabulate f = lambda x: x**3 - x - 2 a, b, rows = 1.0, 2.0, [] for i in range(1, 11): mid = (a + b) / 2 rows.append([i, a, b, mid, f(mid), (b - a) / 2]) if f(a) * f(mid) < 0: b = mid else: a = mid print(tabulate(rows, headers=["iter", "a", "b", "mid", "f(mid)", "error bound"], floatfmt=".6f"))

Output:

iter a b mid f(mid) error bound ------ -------- -------- -------- --------- ------------- 1 1.000000 2.000000 1.500000 -0.125000 0.500000 2 1.500000 2.000000 1.750000 1.609375 0.250000 3 1.500000 1.750000 1.625000 0.666016 0.125000 4 1.500000 1.625000 1.562500 0.252197 0.062500 5 1.500000 1.562500 1.531250 0.059113 0.031250 6 1.500000 1.531250 1.515625 -0.034054 0.015625 7 1.515625 1.531250 1.523438 0.012250 0.007812 8 1.515625 1.523438 1.519531 -0.010971 0.003906 9 1.519531 1.523438 1.521484 0.000622 0.001953 10 1.519531 1.521484 1.520508 -0.005179 0.000977
Command Prompt table of Python bisection method iterations showing a, b, midpoint, f(mid) and error boundTen iterations: a and b squeeze together and the error bound drops from 0.5 to under 0.001.

tabulate formats the rows. Here’s another numeric method that also starts from a simple loop: solving a quadratic equation in Python.

What happens when there’s no sign change?

If f(a) and f(b) have the same sign, bisection can’t promise a root in between, so the function refuses. With two roots, the interval you choose decides which one you get:

def bisection(f, a, b, tol=1e-6, max_iter=100): fa, fb = f(a), f(b) if fa * fb > 0: raise ValueError(f"f(a) and f(b) must have opposite signs (got {fa:.3f} and {fb:.3f})") for i in range(1, max_iter + 1): mid = (a + b) / 2 fm = f(mid) if fm == 0 or (b - a) / 2 < tol: return mid, i if fa * fm < 0: # root is in the left half b, fb = mid, fm else: # root is in the right half a, fa = mid, fm raise RuntimeError("did not converge") f = lambda x: x**3 - x - 2 try: bisection(f, 2, 3) # f(2) = 4 and f(3) = 22: same sign except ValueError as err: print("ValueError:", err) g = lambda x: x**2 - 4 # roots at -2 and 2 print("[-3, 0] ->", round(bisection(g, -3, 0)[0], 6)) print("[0, 3] ->", round(bisection(g, 0, 3)[0], 6))

Output:

ValueError: f(a) and f(b) must have opposite signs (got 4.000 and 22.000) [-3, 0] -> -2.0 [0, 3] -> 2.0

Plotting the function first (see the chart below) is the quickest way to pick a good starting interval.

Check the answer with SciPy

SciPy has scipy.optimize.bisect, plus brentq, which mixes bisection with faster steps:

from scipy.optimize import bisect, brentq f = lambda x: x**3 - x - 2 print(f"scipy bisect: {bisect(f, 1, 2, xtol=1e-12):.12f}") print(f"scipy brentq: {brentq(f, 1, 2):.12f}") r, info = bisect(f, 1, 2, xtol=1e-12, full_output=True) print("bisect iterations:", info.iterations, "| brentq iterations:", brentq(f, 1, 2, full_output=True)[1].iterations)

Output:

scipy bisect: 1.521379706805 scipy brentq: 1.521379706805 bisect iterations: 40 | brentq iterations: 8

Both agree with the hand-written version. I’d use brentq in real work because it needs far fewer iterations, and stick with bisection when you need guaranteed, easy-to-explain behavior.

Real example: find a car loan’s interest rate

No formula gives you the rate from a payment, so it has to be solved numerically. Here’s a $24,000 car loan paid at $450 a month for 60 months:

def bisection(f, a, b, tol=1e-6, max_iter=100): fa, fb = f(a), f(b) if fa * fb > 0: raise ValueError(f"f(a) and f(b) must have opposite signs (got {fa:.3f} and {fb:.3f})") for i in range(1, max_iter + 1): mid = (a + b) / 2 fm = f(mid) if fm == 0 or (b - a) / 2 < tol: return mid, i if fa * fm < 0: # root is in the left half b, fb = mid, fm else: # root is in the right half a, fa = mid, fm raise RuntimeError("did not converge") principal, payment, months = 24_000.00, 450.00, 60 def balance_gap(r): # payment formula minus the actual payment return principal * r / (1 - (1 + r) ** -months) - payment monthly, steps = bisection(balance_gap, 0.0001, 0.05, tol=1e-10) print(f"monthly rate: {monthly:.6%} | APR: {monthly * 12:.2%} | found in {steps} steps") print(f"total paid: ${payment * months:,.2f} | interest: ${payment * months - principal:,.2f}")

Output:

monthly rate: 0.394571% | APR: 4.73% | found in 29 steps total paid: $27,000.00 | interest: $3,000.00
Command Prompt output of a Python bisection method solving the monthly interest rate and APR of a car loanThe rate that makes the payment formula equal $450.00, plus the total interest paid.

The payment formula uses exponents; see the math module in Python for related functions.

Plot the bisection method in Python

A chart shows why the method is so reliable: the midpoints hop from side to side of the root and close in on it:

import matplotlib.pyplot as plt import numpy as np f = lambda x: x**3 - x - 2 a, b, mids = 1.0, 2.0, [] for _ in range(8): mid = (a + b) / 2 mids.append(mid) a, b = (a, mid) if f(a) * f(mid) < 0 else (mid, b) x = np.linspace(0.8, 2.1, 300) plt.figure(figsize=(8, 4.5)) plt.plot(x, f(x), label="f(x) = x³ - x - 2") plt.axhline(0, color="gray", lw=0.8) plt.scatter(mids, [f(m) for m in mids], c=range(len(mids)), cmap="viridis", zorder=3, label="midpoints") for i, m in enumerate(mids[:4], 1): plt.annotate(str(i), (m, f(m)), textcoords="offset points", xytext=(5, 6)) plt.title("Bisection method closing in on the root") plt.xlabel("x"); plt.ylabel("f(x)"); plt.legend() plt.tight_layout() plt.show()
Matplotlib chart of x cubed minus x minus 2 with colored bisection midpoints converging on the root near 1.52The first midpoints are numbered; later ones crowd together at the root.

Bisection vs other root-finding methods

MethodNeedsSpeedAlways converges?
BisectionSign change on [a, b]Slow (halves each step)Yes, if f is continuous
Newton’s methodDerivative and a good guessVery fast near the rootNo
SecantTwo starting pointsFastNo
Brent (brentq)Sign change on [a, b]FastYes

More math and algorithm guides in Python:

Frequently asked questions

How does the bisection method work in Python?

Start with an interval where f changes sign, test the midpoint, keep the half that still has the sign change, and repeat until the interval is smaller than your tolerance.

How many iterations does bisection need?

About log2((b − a) / tol). An interval of width 1 with a tolerance of 1e-6 needs around 20.

Why does my bisection function raise an error?

f(a) and f(b) have the same sign. Pick an interval where the function crosses zero.

Is there a bisection function in SciPy?

Yes: scipy.optimize.bisect(f, a, b). brentq is usually faster.

Is bisection better than Newton’s method?

It’s slower but always converges for continuous functions with a sign change, and it doesn’t need a derivative.

Where is scipy.optimize.bisect documented?

See scipy.optimize.bisect in the SciPy docs.

Read Entire Article