Solve Ax = b with linalg.solve(A, b). Prefer solve over explicit inverse—faster and more stable. For multiple right-hand sides, reuse factorizations.
Basic solve
import numpy as np
from scipy import linalg
A = np.array([[3., 1.], [1., 2.]])
b = np.array([9., 8.])
x = linalg.solve(A, b)
print('x:', x)
print('residual:', np.linalg.norm(A @ x - b))
Square vs least squares
- Square nonsingular A → unique solution
- Overdetermined (more rows) →
lstsqleast-squares fit - Underdetermined → infinitely many; add constraints or regularization
lu factorization reuse
lu, piv = linalg.lu_factor(A) then linalg.lu_solve((lu, piv), b) when solving many b vectors with same A.
Important interview questions and answers
- Q: Why not inv(A) @ b?
A: Explicit inverse is slower and amplifies numerical errors—solve uses factorization. - Q: Residual check?
A: Compute ||Ax − b|| to verify solution quality after solve.
Self-check
- Write the equation form for linalg.solve.
- When use lstsq instead of solve?
Pitfall: Prefer solve over inv(A) @ b—faster and more stable.
Interview prep
- solve vs inv?
solve uses factorization—prefer over explicit inverse.
- lstsq?
Least squares when overdetermined or rank-deficient.