For a square matrix A, its inverse satisfies A multiplied by its inverse equaling the identity matrix, the same way a number multiplied by its reciprocal equals 1. Not every square matrix has an inverse: a singular matrix, one whose determinant is 0, has no inverse, and np.linalg.inv() raises a LinAlgError if you try to invert one. Matrix inversion is also numerically unstable for matrices that are close to singular, a small determinant, or ill-conditioned, which can amplify floating-point rounding errors significantly in the result.
1Understanding np.linalg.inv()
For a square matrix A, its inverse satisfies A multiplied by its inverse equaling the identity matrix, the same way a number multiplied by its reciprocal equals 1. Not every square matrix has an inverse: a singular matrix, one whose determinant is 0, has no inverse, and np.linalg.inv() raises a LinAlgError if you try to invert one. Matrix inversion is also numerically unstable for matrices that are close to singular, a small determinant, or ill-conditioned, which can amplify floating-point rounding errors significantly in the result.
Avoid computing the inverse of A and multiplying it by b to solve a linear system — use np.linalg.solve(A, b) instead, which is both faster and numerically more stable than explicitly forming the matrix inverse and multiplying by it.
import numpy as np
A = np.array([[4, 7], [2, 6]])
A_inv = np.linalg.inv(A)
print(A_inv)2Practical Example
Here is a real-world application of np.linalg.inv() showing how it is used in production NumPy code.
import numpy as np
A = np.array([[4, 7], [2, 6]])
A_inv = np.linalg.inv(A)
identity = A @ A_inv
print(np.round(identity, 10))3Best Practices
Follow these guidelines when working with np.linalg.inv():
1. Use np.linalg.solve(A, b) instead of computing the inverse of A and multiplying by b when solving a linear system — it's faster and avoids extra numerical error
2. Catch LinAlgError when a matrix might be singular or ill-conditioned, rather than assuming inversion will always succeed
3. Check np.linalg.det(A) is meaningfully nonzero before relying on an inverse for numerically sensitive calculations
Tip: Avoid computing the inverse of A and multiplying it by b to solve a linear system — use np.linalg.solve(A, b) instead, which is both faster and numerically more stable than explicitly forming the matrix inverse and multiplying by it.
import numpy as np
A = np.array([[4, 7], [2, 6]])
A_inv = np.linalg.inv(A)
print(A_inv)