import numpy as np
A = np.array([[1, 3, 6], # Right-hand side
[2, 8, 16],
[2, 6, 12]])
b = np.array([4, 8, 8]) # Left-hand side
solution = np.linalg.solve(A, b)
print(solution)
# Output:
numpy.linalg.LinAlgError: Singular matrix
As we can see, using np.linalg.solve returns a LinAlgError telling us that the matrix (in this case A) is a singular matrix. A singular matrix is one that is not invertible. This means that the system of equations we are trying to solve does not have a unique solution (either none or multiple); np.linalg.solve can't handle this.
By using np.linalg.lstsq (least squares solution) instead, we will at least get one solution.
import numpy as np
A = np.array([[1, 3, 6], # Right-hand side
[2, 8, 16],
[2, 6, 12]])
b = np.array([4, 8, 8]) # Left-hand side
x, residuals, rank, s = np.linalg.lstsq(A, b, rcond=None)
# "rcond=None" sets new default for rcond, see function documentation
print(x) # "x" is the solution
# Output:
[4. 0. 0.]
This is interpreted as![](/wiki/plugins/servlet/confluence/placeholder/unknown-macro?name=mathinline&locale=en_US&version=2)
and![](/wiki/plugins/servlet/confluence/placeholder/unknown-macro?name=mathinline&locale=en_US&version=2)