SciPy optimize.root() Function


scipy.optimize.root() is a SciPy function for finding the roots of a vector-valued function, i.e., solving equations of the form f(x) = 0. It supports various algorithms for root-finding and handles both scalar and multivariable problems.

This function allows users to choose from methods such as 'hybr' (default), 'lm', 'broyden1', 'broyden2', 'anderson', 'diagbroyden', 'krylov', and 'excitingmixing'. It is highly versatile, with options for specifying Jacobians, tolerance levels, and solver-specific parameters.

The output is an OptimizeResult object containing the solution, success flag, and diagnostic information.

Syntax

Following is the syntax of the function scipy.optimize.root() which is used to solve nonlinear equations −

root(fun, x0, args=(), method='hybr', jac=None, tol=None, options={})

Parameters

  • fun(callable): The function whose roots are sought. It should take an array x and return an array of the same shape.
  • x0(array_like): Initial guess for the solution.
  • args(tuple, optional): Extra arguments to pass to the function fun.
  • method(str, optional): The algorithm to use. Options include 'hybr', 'lm', 'broyden1', 'anderson', etc.
  • jac(callable, optional): A function to compute the Jacobian matrix of fun. If not provided then finite differences are used.
  • tol(float, optional): Tolerance for termination.
  • options(dict, optional): Solver-specific options like max iterations or verbosity level.

Return Value

scipy.optimize.root() returns an OptimizeResult object containing the below values −

  • x: The solution array.
  • success: A boolean indicating if the solver succeeded.
  • message: Description of the cause of termination.
  • fun: The residuals at the solution.

Finding Roots of a Nonlinear Function

Heres an example of finding the roots of a nonlinear function using scipy.optimize.root(). Here we will find the solution to the following system of nonlinear equation which is the system represents a circle and a line and we aim to find the point of intersection, i.e., the root of the system −

import numpy as np
from scipy.optimize import root

# Define the nonlinear system of equations
def fun(x):
    return [x[0]**2 + x[1]**2 - 4,  # Circle equation
            x[0] - x[1]]            # Line equation

# Initial guess for the solution
x0 = [1, 1]

# Solve the system of nonlinear equations
result = root(fun, x0)

# Display the results
print("Solution:", result.x)
print("Success:", result.success)
print("Message:", result.message)

Following is the output of the function scipy.optimize.root() which is used to find roots of a non linear function −

Solution: [1.41421356 1.41421356]
Success: True
Message: The solution converged.

Solving a System of Linear Equations

To solve a system of linear equations using scipy.optimize.root() we can represent the system as a set of equations of the form Ax=b where A is a matrix and b is a vector. In this example our goal is to find the vector x that satisfies this system −

import numpy as np
from scipy.optimize import root

# Define the linear system Ax = b
A = np.array([[3, 2], [1, 4]])
b = np.array([6, 8])

# Define the function for the system of linear equations
def fun(x):
    return np.dot(A, x) - b

# Initial guess for the solution
x0 = [0, 0]

# Solve the system
result = root(fun, x0)

# Display the results
print("Solution:", result.x)
print("Success:", result.success)
print("Message:", result.message)

Here is the output of the function scipy.optimize.root() which is used to solve a system of linear equation −

Solution: [0.8 1.8]
Success: True
Message: The solution converged.

Finding the Root Multiple functions

Here in this example we will solve for the roots of multiple function involving multiple variables for the equations f1(x,y) = ex+y2-1 = 0 and f2(x,y) = x3+3x2+1 = 0

import numpy as np
from scipy.optimize import root

# Define the system of nonlinear equations
def fun_system(vars):
    x, y = vars
    # f1(x, y) = e^x + y^2 - 1
    # f2(x, y) = x^3 - 3x + 1
    f1 = np.exp(x) + y**2 - 1
    f2 = x**3 - 3*x + 1
    return [f1, f2]  # Return both residuals

# Initial guess for [x, y]
initial_guess = [0.0, 0.0]

# Use root to solve the system of equations
result = root(fun_system, initial_guess)

# Display the result
if result.success:
    print(f"Roots found: x = {result.x[0]}, y = {result.x[1]}")
else:
    print(f"Root finding failed: {result.message}")

Here is the output of the function scipy.optimize.root() which is used to find the root of multiple functions −

Root finding failed: The iteration is not making good progress, as measured by the
  improvement from the last ten iterations.
scipy_optimize.htm
Advertisements