SciPy Root Finding

SciPy Root Finding#

import numpy as np
from scipy import optimize

The SciPy library has root finders in the optimize module: https://docs.scipy.org/doc/scipy/reference/optimize.html

The general purpose root finder for a single variable is optimize.brentq which implements Brent’s method. This is a mix of bisection and something like Newton’s method.

Like bisection, Brent’s method requires you to provide an interval in which to find the root.

Let’s try it on the same functions as we did previously

def f(x):
    return 0.5*x**3 + np.pi/3 * x + 2
r = optimize.brentq(f, -2, 2)
r
-1.1615652985544285
def h(x):
    return x**4 - 2*x**3 + 1
r = optimize.brentq(h, 1.1, 2)
r
1.839286755214158