15.5 Root Finding Using SciPy

Contents

15.5 Root Finding Using SciPy#

Although you are required to write your own solutions for the root finding methods in this module, in production code it would be more appropriate to use the root finding methods from SciPy where possible.

The function root_scalar() from the scipy.optimize module can be used to find the roots of an equation. The function can be imported using:

from scipy.optimize import root_scalar

We shall not unpack all of the arguments of root_scalar() here, so you are encouraged to read further in the documentation. The first and most important positional argument is the function to find the roots of, referred to as f. This should take a single argument. All other arguments are optional keyword arguments, though for the function to produce results some of these are required.

One keyword argument is method, which is a string to indicate which method should be used. These will be listed below. If this is omitted, a method will be automatically selected based on which other keyword arguments are provided. Unless you require that a particular method is used, it is recommended to allow the function to select the appropriate method.

Some of the keyword arguments are required depending on which method should be used, these are:

  • bracket - an interval containing the root

  • x0 - initial guess for the root

  • x1 - a second guess for the root

  • fprime - the derivative of f

  • fprime2 - the second derivative of f

The root_scalar() function returns a RootResults object, the attributes of immediate importance to us are:

  • root - estimated root

  • iterations - number of iterations needed to find the root

  • converged - True if converged to root

Methods#

Here we will briefly discuss the methods used in the root_scalar() function. Links to SciPy documentation on specific functions for each of these methods are provided, where you can find additional reading and sources if you want to understand these methods. The methods are listed in the table below, along with a brief description and list of required keyword arguments.

Method (string)

Description

Required Keyword Arguments

'bisect'

Bisection method as covered in this course (see bisect for more).

bracket

'brentq'

Brent’s method, generally considered the best in SciPy (See brentq for more).

bracket

'brenth'

Brent’s method with hyperbolic extrapolation (See brenth for more)

bracket

'ridder'

Ridder’s method (See ridder for more)

bracket

'toms748'

TOMS Algorithm 748 method (see toms748 for more)

bracket

'newton'

Newton-Raphson’s method as covered in this course (see newton for more).

x0, fprime (optional)

secant'

Secant method as covered in this course (see newton for more)

x0, x1 (optional)

'halley'

Halley’s method (see newton for more).

x0, fprime, fprime2