root() takes a function fun and an initial guess x0, then iteratively refines that guess until it converges on a point where fun(x) is approximately zero, returning a result object whose .x attribute holds the solution and whose .success attribute reports whether the algorithm actually converged. It works for both single equations and systems of multiple simultaneous equations, when fun returns an array of residuals instead of a single value, and the method parameter selects between several different underlying numerical algorithms, each with different convergence properties for different kinds of problems.
1Understanding optimize.root()
root() takes a function fun and an initial guess x0, then iteratively refines that guess until it converges on a point where fun(x) is approximately zero, returning a result object whose .x attribute holds the solution and whose .success attribute reports whether the algorithm actually converged. It works for both single equations and systems of multiple simultaneous equations, when fun returns an array of residuals instead of a single value, and the method parameter selects between several different underlying numerical algorithms, each with different convergence properties for different kinds of problems.
Always check result.success after calling root() — a non-converging call still returns a result object with an .x value, but that value may be meaningless if the algorithm never actually found a root, so don't blindly trust .x without checking success first.
from scipy import optimize
def f(x):
return x**2 - 4
result = optimize.root(f, x0=1)
print(result.x)2Practical Example
Here is a real-world application of optimize.root() showing how it is used in production SciPy code.
from scipy import optimize
def f(x):
return x**2 - 4
result = optimize.root(f, x0=-1)
print(result.x)3Best Practices
Follow these guidelines when working with optimize.root():
1. Always check result.success before trusting result.x, since a failed convergence still returns a potentially meaningless x value
2. Provide a reasonably close initial guess x0 when possible, since root-finding algorithms can converge to the wrong root, or fail to converge at all, from a poor starting point
3. Use root() for systems of equations by having fun return an array of residuals, one per equation, rather than trying to solve each equation separately
Tip: Always check result.success after calling root() — a non-converging call still returns a result object with an .x value, but that value may be meaningless if the algorithm never actually found a root, so don't blindly trust .x without checking success first.
from scipy import optimize
def f(x):
return x**2 - 4
result = optimize.root(f, x0=1)
print(result.x)