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 rootx0
- initial guess for the rootx1
- a second guess for the rootfprime
- the derivative off
fprime2
- the second derivative off
The root_scalar()
function returns a RootResults
object, the attributes of immediate importance to us are:
root
- estimated rootiterations
- number of iterations needed to find the rootconverged
- 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 |
---|---|---|
|
Bisection method as covered in this course (see |
|
|
Brent’s method, generally considered the best in SciPy (See |
|
|
Brent’s method with hyperbolic extrapolation (See |
|
|
Ridder’s method (See |
|
|
TOMS Algorithm 748 method (see |
|
|
Newton-Raphson’s method as covered in this course (see |
|
‘ |
Secant method as covered in this course (see |
|
|
Halley’s method (see |
|