The np.linalg.solve() function solves a linear system of equations, represented as Ax = b, where A is a square matrix, x is the unknown vector, and b is the constant vector. The function computes the values of x that satisfy the given linear system.
Syntax
numpy.linalg.solve(arr1, arr2 )
Parameters
The numpy linalg solve() function takes two main parameters, which are:
- arr1: This is array 1, a “Coefficient matrix”.
- arr2: This is array 2, an Ordinate or “dependent variable” values matrix.
Return Value
The linalg solve() function returns the equation ax=b; the returned type is a matrix with a shape identical to matrix b. This function returns LinAlgError if our first matrix (a) is singular or not square.
Example
# Program to show the working of solve()
import numpy as np
# creating the array "a"
A = np.array([[3, 4, 5], [1, 2, 3], [2, 4, 5]])
B = np.array([9, 8, 7])
print("Array A is: \n", A)
print("Array B is : \n", B)
# Calculating the equation
ans = np.linalg.solve(A, B)
# Printing the answer
print("Answer of the equation is :\n", ans)
# Checking if the answer if correct
print(np.allclose(np.dot(A, ans), B))
Output
Array A is:
[[3 4 5]
[1 2 3]
[2 4 5]]
Array B is :
[9 8 7]
Answer of the equation is :
[ 2. -10.5 9. ]
True
Explanation
In this example, we have created a 3×3 square matrix, which is not singular, and we have printed that.
Then, we created an array of size 3 and printed that also.
Then, we have called numpy.linalg.solve() to calculate the equation Ax=B. We can see that we have got an output of shape inverse of B.
Also, at last, we checked whether the returned answer was True.
That’s it.