Rootfinding in Practice
Production root finders combine the methods of this section: they keep a bracket for safety, take fast interpolation steps when they help, and fall back to bisection when they do not. This lesson looks at Brent's method, at the SciPy interfaces, and at the practical questions: finding brackets, handling several roots, and choosing tolerances.
Brent's method
Brent's method (1973), building on Dekker's, maintains a bracket with a sign change and at each step tries, in order:
- inverse quadratic interpolation through the last three points;
- a secant step if only two distinct points are usable;
- bisection if the interpolated point falls outside the bracket or progress is too slow.
It never needs more than about evaluations and usually converges superlinearly, so it is as safe as bisection and nearly as fast as the secant method.
import numpy as np
from scipy.optimize import root_scalar
count = {"n": 0}
def f(x):
count["n"] += 1
return np.cos(x) - x**3
for method in ("bisect", "brentq", "ridder", "toms748"):
count["n"] = 0
sol = root_scalar(f, bracket=[0, 1], method=method, xtol=1e-14)
print(f"{method:8s}: root {sol.root:.14f}, function calls {count['n']}")bisect : root 0.86547403310161, function calls 49
brentq : root 0.86547403310162, function calls 9
ridder : root 0.86547403310162, function calls 16
toms748 : root 0.86547403310161, function calls 9
Finding brackets
A bracket requires knowing where to look. Strategies:
- Physical reasoning (a probability is in , a temperature is positive).
- Sampling on a grid and looking for sign changes, which also finds several roots at once.
- Expanding an interval geometrically from a guess until the sign changes.
import numpy as np
from scipy.optimize import brentq
f = lambda x: np.sin(3 * x) - 0.5 * x
x = np.linspace(-4, 4, 401)
y = f(x)
idx = np.where(np.sign(y[:-1]) * np.sign(y[1:]) < 0)[0]
roots = [brentq(f, x[i], x[i + 1]) for i in idx]
exact_zero = x[np.where(y == 0)[0]]
print(f"{len(roots)} sign changes; roots:", np.round(roots, 6))
print("grid points that are exact roots:", exact_zero)2 sign changes; roots: [-0.892928 0.892928]
grid points that are exact roots: [0.]
The grid must be fine enough not to step over two close roots, and roots exactly on grid points (here ) must be checked separately. Double roots (no sign change) are invisible to this search; minimize or look at to find them.
Polynomials
For polynomial roots use np.roots, which computes the eigenvalues of the companion matrix with the QR algorithm (The QR Algorithm). It returns all roots, complex ones included, without guesses.
import numpy as np
coeffs = [1, 0, -7, 6] # x^3 - 7x + 6 = (x - 1)(x - 2)(x + 3)
print("np.roots:", np.sort(np.roots(coeffs)))
C = np.array([[0, 7, -6], [1, 0, 0], [0, 1, 0]], dtype=float) # companion matrix
print("eigenvalues of companion:", np.sort(np.linalg.eigvals(C)))np.roots: [-3. 1. 2.]
eigenvalues of companion: [-3. 1. 2.]
Choosing a method
| Situation | Method |
|---|---|
| bracket known, 1 variable | brentq (default choice) |
| good guess and cheap derivative | Newton (newton with fprime) |
| good guess, no derivative | secant (newton without fprime) |
| polynomial | np.roots |
| system of equations | scipy.optimize.root (hybr, lm, broyden1, krylov) |
| many independent scalar problems | vectorized Newton in NumPy |
Tolerances
xtol (absolute) and rtol (relative) stop the iteration on the bracket width or step; a residual check catches discontinuities. Do not ask for more accuracy than the conditioning allows: if is computed with error , the root is only determined to about (The Rootfinding Problem).
In software
scipy.optimize.root_scalaris the unified interface for one variable;brentqandtoms748are the recommended bracketing methods.- Event detection in
solve_ivp(stop the simulation when a ball hits the floor) uses a bracketing root finder on the interpolated solution.
Exercises
Exercise 1: Which method?
You must invert for one million values of in . Which approach do you choose?
Answer
A vectorized Newton iteration from .
Solution
has , so Newton converges from for every , and a few NumPy array operations solve all million problems at once. A loop of brentq calls would be much slower.
Exercise 2: Grid spacing
Roots of in are to be found by sampling. Is a grid of 101 points fine enough? And 21 points?
Answer
101 points (spacing ) is fine; 21 points (spacing ) misses many roots, which are only apart.
Solution
Two roots inside one grid cell produce no sign change at the cell ends. The grid spacing must be smaller than the smallest distance between roots; here is fine, is not.
Exercise 3: Vectorized Newton (code)
Solve for with 6 vectorized Newton steps and report the largest residual.
Answer
The residual is at rounding level (here exactly ).
Solution
import numpy as np
y = np.arange(10.0)
x = y.copy()
for _ in range(6):
x -= (x + 0.3 * np.sin(x) - y) / (1 + 0.3 * np.cos(x))
print(np.round(x, 6))
print(f"max residual {np.max(np.abs(x + 0.3 * np.sin(x) - y)):.1e}")[0. 0.787436 1.702602 2.939902 4.271284 5.256653 6.064952 6.841159
7.703395 8.832532]
max residual 0.0e+00
Test yourself
Brent's method combines…
- Newton and Halley
- bisection, secant and inverse quadratic interpolation
- only bisection
- fixed-point iteration and Aitken
How does np.roots find polynomial roots?
- Newton from random starts
- Eigenvalues of the companion matrix
- Bisection
- The quadratic formula repeatedly
Why can a sign-change search miss a root of ?
- The grid is too fine
- There is no sign change at a double root
- Roots must be integers
- It cannot miss it