SciPy - solve() Function



The scipy.linalg.solve() function is used to solve a system of linear equations of the form −

Ax = B

Where A is the square matrix (nn), constants of the system are represented in vector or matrix B that is in nm shape. The solution of the system is an unknown vector or matrix x.

The solve() method will raise ValueError if there are size discrepancies or the input matrix A is not square. If the matrix is singular (non-invertible), regardless of symmetry, it produces a LinAlgError. If the input matrix is complex and transposed=True, a NotImplementedError will occur; if the input matrix is ill-conditioned, a LinAlgWarning may be raised.

Syntax

Following is the syntax of the SciPy solve() method −

scipy.linalg.solve(a, b,lower=False, overwrite_a=False, overwrite_b=False, check_finite=True, assume_a='gen', transposed=False)

Parameters

Following are the parameters of solve() method

  • a (array_like, shape (n, n)) − Coefficient matrix A.

  • b array_like, shape (n,) or (n, k) − Input equation of Right-hand side.

  • lower (bool, optional) − If true the matrix uses the data only in the lower triangle of A, entries above the diagonal are ignored. If false the matrix uses the data in the upper triangle of A, entries below the diagonal are ignored. By default it is false.

  • overwrite_a (bool, optional) − If True, the input matrix A will be overwritten, which may save memory but can modify the original matrix. Default is False.

  • overwrite_b (bool, optional) − If True, the input matrix B will be overwritten. Default is False.

  • check_finite (bool, optional)− If True, it checks whether the A and B contain only valid numbers (no NaNs or Infs). Disabling this parameter will speed up the process if you are confident that the data is valid.

  • assume_a str, {'gen', 'sym', 'her', 'pos'}, optional, default 'gen' − To use a specialized solver for specific types of matrices we use assume_a parameter.

    • 'gen': General matrix(default).

    • 'sym': Symmetric matrix.

    • 'her': Hermitian matrix.

    • 'pos': Positive definite matrix.

  • transposed (bool, optional) − If True, solve for A^T x = b, assuming A is transposed. Default is false.

Return Value

x: ndarray, shape (n,) or (n, k). The solution to the system Ax = B, where x satisfies the equation.

Example 1: Solve Linear Equations with SciPy's solve()

In the below example we have created a Coefficient matrix A and Input data(right hand side of the equation) B. With the help of solve() method we will solve system of equation Ax = B. Result is the solution vector x.

import numpy as np
from scipy.linalg import solve

# Define a matrix A
A = np.array([[2, 1], [5, 7]])

# Define a right-hand side matrix B
B = np.array([11, 13])

# Solve for X such that AX = B
x = solve(A, b)
print("Solution x:", x)

When we run above the program, it produces the following result

Solution x: [ 7.11111111 -3.22222222]

Example 2: Optimize Symmetric Matrices using assume_a='sym'

We can use the assume_a='sym' parameter to optimize solving for symmetric coefficient matrices, which can be inverted if their determinant is non-zero.

In the below example, let us create a Symmetric matrix A and use the assume_a parameter to solve the equation. Following is the code −

import numpy as np
from scipy.linalg import solve

A = np.array([[4, 1], [1, 3]])
b = np.array([1, 2])
x = solve(A, b, assume_a='sym')
print("Solution x:", x)

Following is an output of the above code

Solution x: [0.09090909 0.63636364]

Example 3: Verify Solutions with np.dot() and solve()

In the below code, we have inputs A, b and solve x using scipy.linalg.solve() for the equation Ax=b and verify the solution using np.dot() function.

import numpy as np
from scipy import linalg

A = np.array([[1, 2], [3, 4]])
b = np.array([5, 11])
x = linalg.solve(A, b)
print("Solution x:", x)
#verifying the solution
print("Verification (A * x == b):", np.allclose(np.dot(A, x), b))

Output of the above code is as follows

Solution x: [1. 2.]
Verification (A * x == b): True

Example 4: Solve Invertible Matrices with Non-Zero Determinants

Only if a square matrix has a non-zero determinant it can be inverted.

Construct a matrix A and find the determinant. If this determinant is zero, the matrix is invertible, so we can solve x with the solve() method.

import numpy as np
from scipy.linalg import solve, det

A = np.array([[4, 2], [3, 1]])
b = np.array([10, 7])

# Check if determinant is non-zero
if det(A) != 0:
    x = solve(A, b)
    print("Solution x:", x)
else:
    print("Matrix is singular and cannot be solved.")

Output of the above code is as follows

Solution x: [2. 1.]

Example 5: Solving for Matrix solution (x)

When B is a matrix, scipy.linalg.solve() solves the system so that X is a matrix with the same shape as B.

In this example, A is a square matrix, while B is a multi-column matrix. AX=B is satisfied by computing the solution X.

import numpy as np
from scipy.linalg import solve

A = np.array([[3, 1], [1, 2]])
B = np.array([[5, 6], [7, 8]])
X = solve(A, B)
print("\nSolution Matrix X:\n", X)

# Verify the solution by checking if A @ X = B
verification = np.allclose(np.dot(A, X), B)
print("\nVerification (A @ X == B):", verification)

Output of the above code is as follows

Solution Matrix X:
 [[0.6 0.8]
 [3.2 3.6]]

Verification (A @ X == B): True
scipy_linalg.htm
Advertisements