Solving Linear Equations using NumPy
Examples
Next Topic ⮕Eigenvalues, Eigenvectors, and Diagonalization in NumPy
Introduction
One of the most practical applications of linear algebra in programming is solving systems of linear equations. Whether you're working on data science, engineering simulations, or economic models — systems like Ax = B
pop up often.
With NumPy, Python gives us the numpy.linalg.solve()
method — a fast, reliable way to solve such problems.
What is a Linear Equation System?
In mathematics, a system of linear equations looks like this:
2x + 3y = 8
3x + 4y = 11
We can represent this system in matrix form:
A = [[2, 3],
[3, 4]]
B = [8, 11]
Our goal is to find the values of x
and y
that satisfy this equation. In matrix terms, we solve:
Ax = B
Step-by-Step: Solving Ax = B using NumPy
1. Import NumPy
import numpy as np
2. Define the Coefficient Matrix A
A = np.array([[2, 3],
[3, 4]])
3. Define the Right-Hand Side Vector B
B = np.array([8, 11])
4. Solve Using numpy.linalg.solve()
x = np.linalg.solve(A, B)
print("Solution:", x)
Solution: [1. 2.]
This means: x = 1, y = 2
Verifying the Solution
How do we know that x = 1
and y = 2
are correct? We can multiply the matrix A
with the result x
and compare it to B
:
print("Check:", np.dot(A, x))
[ 8. 11.]
Since the output matches our original vector B
, our solution is correct.
Important Checks and Considerations
- Matrix A must be square: The number of equations should match the number of unknowns.
- Matrix A must be invertible (non-singular): If not, NumPy will throw a
LinAlgError
.
Example: What happens when A is not invertible?
A = np.array([[1, 2],
[2, 4]])
B = np.array([5, 10])
x = np.linalg.solve(A, B)
LinAlgError: Singular matrix
This means the system either has no solution or infinitely many solutions. In such cases, we may need to use np.linalg.lstsq()
for a least squares solution.
Real-World Insight
Solving linear equations isn’t just a textbook problem — it’s the backbone of real-world applications like recommendation systems, financial modeling, and physics simulations. Mastering this skill opens up the power of matrix-based thinking.
Conclusion
With NumPy, solving linear systems becomes both intuitive and powerful. By using numpy.linalg.solve()
, you're leveraging an optimized, reliable tool to solve problems that appear across science and industry.
As you continue through this course, keep applying what you’ve learned in small projects — that’s where theory becomes skill.
What’s Next?
In the next lesson, we’ll go deeper into matrix operations like calculating determinants and inverses, and how they relate to solving equations.