TExcelTAD
Home › SciPy › SciPy Root Finding

SciPy Root Finding

A root of a function is an input where the function equals zero. Many practical questions turn into root finding once you move everything to one side of the equation: At what interest rate does this loan cost exactly 10 000? When does the ball hit the ground? Where do two curves cross? scipy.optimize offers robust root finders for one equation and for systems of equations.

Bracketing methods

If you can find two points a and b where f(a) and f(b) have opposite signs, a continuous function must cross zero somewhere between them. Bracketing methods exploit this and are guaranteed to converge. brentq is the recommended one:

python · try it yourself
from scipy.optimize import brentq, bisect

def f(x):
    return x ** 3 - 2 * x - 5

print("f(2) =", f(2), " f(3) =", f(3))       # opposite signs: a root is between

root = brentq(f, 2, 3)
print(f"brentq root : {root:.10f}")
print(f"f(root)     : {f(root):.1e}")

root_b, info = bisect(f, 2, 3, full_output=True)
print(f"bisect root : {root_b:.10f} after {info.iterations} iterations")
root_q, info_q = brentq(f, 2, 3, full_output=True)
print(f"brentq used : {info_q.iterations} iterations")
f(2) = -1  f(3) = 16
brentq root : 2.0945514815
f(root)     : 3.6e-15
bisect root : 2.0945514815 after 39 iterations
brentq used : 7 iterations

Brent's method combines bisection's safety with faster interpolation steps, so it needs far fewer iterations.

root_scalar: one interface for all methods

root_scalar() wraps every scalar method. With a bracket it uses Brent; with a starting point and a derivative it can use Newton's method, which converges very fast near the root:

python · try it yourself
import numpy as np
from scipy.optimize import root_scalar

# Solve cos(x) = x
f = lambda x: np.cos(x) - x
df = lambda x: -np.sin(x) - 1

r1 = root_scalar(f, bracket=[0, 1])
r2 = root_scalar(f, x0=1.0, fprime=df, method="newton")
print(f"brentq : x = {r1.root:.12f}, evaluations = {r1.function_calls}")
print(f"newton : x = {r2.root:.12f}, evaluations = {r2.function_calls}")
print("converged:", r1.converged and r2.converged)
brentq : x = 0.739085133215, evaluations = 8
newton : x = 0.739085133215, evaluations = 8
converged: True

Both reach the same 12-digit answer within a handful of evaluations (Newton's count includes its derivative calls). Newton's real advantage is that it needs no bracket, only a starting point; the price is that from a bad start it can wander off or fail, while a bracketing method cannot.

Method Needs Guaranteed? Speed
bisect bracket yes slow
brentq / brenth bracket yes fast
ridder, toms748 bracket yes fast
newton x0 + derivative no very fast near the root
secant x0 (and x1) no fast
halley x0 + 1st and 2nd derivatives no very fast

A practical example: interest rate of a loan

A loan of 10 000 is repaid with 24 monthly payments of 460. What monthly interest rate does that imply? The present value of the payments must equal the loan, so we look for the rate where the difference is zero:

python · try it yourself
from scipy.optimize import brentq

loan, payment, months = 10_000, 460, 24

def pv_gap(rate):
    present_value = payment * (1 - (1 + rate) ** -months) / rate
    return present_value - loan

monthly = brentq(pv_gap, 1e-6, 0.1)
print(f"monthly rate : {monthly:.4%}")
print(f"annual (APR) : {12 * monthly:.2%}")
print(f"total paid   : {payment * months}")
monthly rate : 0.8071%
annual (APR) : 9.69%
total paid   : 11040

Systems of non-linear equations

root() solves several equations in several unknowns at once. Return a list of residuals, one per equation. Here we find where a circle of radius 3 crosses the parabola y = x² − 1:

python · try it yourself
import numpy as np
from scipy.optimize import root

def equations(p):
    x, y = p
    return [x ** 2 + y ** 2 - 9,     # circle
            y - (x ** 2 - 1)]        # parabola

for guess in ([2, 2], [-2, 2]):
    sol = root(equations, guess)
    x, y = sol.x
    print(f"start {guess} -> x = {x:.6f}, y = {y:.6f}, success = {sol.success}")
start [2, 2] -> x = 1.836377, y = 2.372281, success = True
start [-2, 2] -> x = -1.836377, y = 2.372281, success = True

Different starting guesses lead to different solutions — non-linear systems may have several roots, and root() finds the one nearest its start.

Finding all roots in an interval

A bracketing method finds only one root at a time. A simple strategy for several roots: sample the function on a grid, look for sign changes, and refine each bracket with brentq:

python · try it yourself
import numpy as np
from scipy.optimize import brentq

def f(x):
    return np.sin(x) - 0.3 * x

grid = np.linspace(-5, 5, 100)
values = f(grid)
roots = [brentq(f, a, b)
         for a, b, fa, fb in zip(grid[:-1], grid[1:], values[:-1], values[1:])
         if fa * fb < 0]
print("roots:", np.round(roots, 6))
roots: [-2.356441  0.        2.356441]

Note: A grid can miss two roots that are closer together than the grid spacing (the function dips below zero and back between samples). Use a finer grid if you suspect roots close together, and remember an exact root that falls on a grid point gives fa * fb == 0.

Test yourself

What does brentq require to start?

  1. A derivative
  2. A single starting point
  3. Two points where the function has opposite signs
  4. The exact root

Which method is fastest near the root but not guaranteed to converge?

  1. bisect
  2. brentq
  3. newton
  4. ridder

Which function solves a system of several non-linear equations?

  1. brentq
  2. root
  3. bisect
  4. minimize_scalar