Bisection Method in Python
Trap a root between two points and halve the interval until it is as small as you need.
- The sign-change rule f(a) * f(b) < 0
- Halving the interval in a loop
- How many steps a tolerance needs
- 1
[1, 2]f(1) < 0, f(2) > 0 - 2
[1.5, 2]f(1.5) < 0: keep the right half - 3
[1.5, 1.75]f(1.75) > 0: keep the left half - 4
1.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.
a, b🔢 The range the number is inmid = (a + b) / 2🎯 Guess the middlef(a) * f(mid) <= 0↕️ Higher or lower? Keep that half(b - a) / 2 > tol🔁 Keep guessing until the range is tinyThe 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
f(a) * f(b) > 0means no sign change, so the function raisesValueError.- Each step computes
midand keeps either[a, mid]or[mid, b]. - The interval halves every step, so
tol=1e-6takes 19 steps andtol=1e-12takes 39. - 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.brentqconverge much faster. - The function touches zero without changing sign, like x**2: bisection cannot find that root.
Example code
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)
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.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Not checking for a sign change
Without the check the loop still returns a number, but it is not a root.
def bisection(f, a, b, tol=1e-6):
while (b - a) / 2 > tol:
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.
while f(mid) != 0:
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 challengesTools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.