np.linalg.solve(A, b) finds x such that A times x equals b, using an efficient and numerically stable algorithm, LU decomposition under the hood, rather than explicitly computing A's inverse and multiplying — computing an inverse and then multiplying is both slower and introduces more floating-point error than solve()'s direct approach. A must be square and non-singular, invertible; if it isn't, solve() raises a LinAlgError.
1Understanding np.linalg.solve()
np.linalg.solve(A, b) finds x such that A times x equals b, using an efficient and numerically stable algorithm, LU decomposition under the hood, rather than explicitly computing A's inverse and multiplying — computing an inverse and then multiplying is both slower and introduces more floating-point error than solve()'s direct approach. A must be square and non-singular, invertible; if it isn't, solve() raises a LinAlgError.
Always prefer np.linalg.solve(A, b) over computing the inverse of A and multiplying by b — solving directly is both faster and numerically more accurate, since it avoids the extra rounding error introduced by explicitly forming the inverse matrix.
import numpy as np
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])
x = np.linalg.solve(A, b)
print(x)2Practical Example
Here is a real-world application of np.linalg.solve() showing how it is used in production NumPy code.
import numpy as np
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])
x = np.linalg.solve(A, b)
print(np.allclose(A @ x, b))3Best Practices
Follow these guidelines when working with np.linalg.solve():
1. Use np.linalg.solve(A, b) instead of computing the inverse of A and multiplying by b whenever you're solving a linear system, for speed and numerical accuracy
2. Catch LinAlgError to handle the case where A is singular or not solvable, rather than assuming a solution always exists
3. Use np.linalg.lstsq() instead of solve() when the system is overdetermined or underdetermined, a non-square A, since solve() specifically requires a square matrix
Tip: Always prefer np.linalg.solve(A, b) over computing the inverse of A and multiplying by b — solving directly is both faster and numerically more accurate, since it avoids the extra rounding error introduced by explicitly forming the inverse matrix.
import numpy as np
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])
x = np.linalg.solve(A, b)
print(x)