TExcelTAD
Home › Numerical Methods › Rootfinding in Practice

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 [a,b][a, b] with a sign change and at each step tries, in order:

  1. inverse quadratic interpolation through the last three points;
  2. a secant step if only two distinct points are usable;
  3. bisection if the interpolated point falls outside the bracket or progress is too slow.

It never needs more than about (log⁡2b−aτ)2(\log_2\frac{b - a}{\tau})^2 evaluations and usually converges superlinearly, so it is as safe as bisection and nearly as fast as the secant method.

python · try it yourself
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 [0,1][0, 1], a temperature is positive).
  • Sampling ff 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.
python · try it yourself
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 x=0x = 0) must be checked separately. Double roots (no sign change) are invisible to this search; minimize ∣f∣\lvert f\rvert or look at f′f' 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.

python · try it yourself
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 ff is computed with error δ\delta, the root is only determined to about δ∣f′(r)∣\frac{\delta}{\lvert f'(r)\rvert} (The Rootfinding Problem).

In software

  • scipy.optimize.root_scalar is the unified interface for one variable; brentq and toms748 are 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 y=x+0.3sin⁡xy = x + 0.3\sin x for one million values of yy in [0,10][0, 10]. Which approach do you choose?

Answer

A vectorized Newton iteration from x0=yx_0 = y.

Solution

f(x)=x+0.3sin⁡x−yf(x) = x + 0.3\sin x - y has f′(x)=1+0.3cos⁡x≥0.7f'(x) = 1 + 0.3\cos x \ge 0.7, so Newton converges from x0=yx_0 = y for every yy, 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 f(x)=sin⁡(50x)f(x) = \sin(50x) in [0,2][0, 2] are to be found by sampling. Is a grid of 101 points fine enough? And 21 points?

Answer

101 points (spacing 0.020.02) is fine; 21 points (spacing 0.10.1) misses many roots, which are only π50≈0.063\frac{\pi}{50} \approx 0.063 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 0.02<0.0630.02 < 0.063 is fine, 0.10.1 is not.

Exercise 3: Vectorized Newton (code)

Solve x+0.3sin⁡x=yx + 0.3\sin x = y for y=0,1,…,9y = 0, 1, \ldots, 9 with 6 vectorized Newton steps and report the largest residual.

Answer

The residual is at rounding level (here exactly 00).

Solution
python · try it yourself
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…

  1. Newton and Halley
  2. bisection, secant and inverse quadratic interpolation
  3. only bisection
  4. fixed-point iteration and Aitken

How does np.roots find polynomial roots?

  1. Newton from random starts
  2. Eigenvalues of the companion matrix
  3. Bisection
  4. The quadratic formula repeatedly

Why can a sign-change search miss a root of f(x)=(x−2)2f(x) = (x - 2)^2?

  1. The grid is too fine
  2. There is no sign change at a double root
  3. Roots must be integers
  4. It cannot miss it