What is the np.linalg.solve() Method

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.


numpy.linalg.solve(arr1, arr2 )


The numpy linalg solve() function takes two main parameters, which are:

  1. arr1: This is array 1, a “Coefficient matrix”.
  2. 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.


# 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))


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. ]


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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.