Solve a System of Linear Equations with numpy.linalg.solve
Write the equations as a matrix A and a vector b, then let np.linalg.solve find every unknown at once.
- Writing equations as A x = b
- np.linalg.solve and checking with np.allclose
- What happens with a singular matrix
Equations as a matrix
The problem
Circuits, chemical equations, mixtures and balance problems all lead to several linear equations with several unknowns. Substitution works for two equations, but with three or more it gets long and easy to get wrong.
Think of it like this
A system of equations is like a set of shopping receipts: each receipt lists how many of each item you bought and the total paid. From enough receipts you can work out the price of every item, and np.linalg.solve does exactly that.
A🧾 How many of each item is on each receiptb💰 The total on each receiptnp.linalg.solve(A, b)🔍 Work out the price of each itemnp.allclose(A @ x, b)✅ Check the prices add up to the totalsA linear system is a set of equations like 2x + y - z = 8 that can be written as A @ x = b. np.linalg.solve(A, b) returns the vector x that satisfies every equation.
Key points
- Each row of
Ais one equation, each column one unknown. bholds the right-hand sides, in the same order as the rows.np.allclose(A @ solution, b)checks the answer while allowing for rounding.- A singular matrix raises
np.linalg.LinAlgError: there is no unique solution.
When should you use it?
- Electric circuits with Kirchhoff's laws.
- Balancing chemical equations and mixture problems.
- The linear algebra step inside regression and simulations.
When not to use it
- More equations than unknowns with no exact solution: use
np.linalg.lstsq. - Equations with symbols instead of numbers: use
sympy.solve.
Example code
import numpy as np
# 2x + y - z = 8
# -3x - y + 2z = -11
# -2x + y + 2z = -3
A = np.array([[2, 1, -1],
[-3, -1, 2],
[-2, 1, 2]], dtype=float)
b = np.array([8, -11, -3], dtype=float)
solution = np.linalg.solve(A, b)
x, y, z = solution
print(f"x = {x:.4f}, y = {y:.4f}, z = {z:.4f}")
# Check: A @ solution should give b back
print("A @ solution =", (A @ solution).round(6).tolist())
print("Correct:", np.allclose(A @ solution, b))
# A singular matrix (rows are multiples) has no unique solution
B = np.array([[1, 2], [2, 4]], dtype=float)
try:
np.linalg.solve(B, np.array([3, 6], dtype=float))
except np.linalg.LinAlgError as error:
print("Singular matrix:", error)
Result of running the code
x = 2.0000, y = 3.0000, z = -1.0000
A @ solution = [8.0, -11.0, -3.0]
Correct: True
Singular matrix: Singular matrix
Code explanation
Each row of A is one equation and each column one unknown, so A is 3 x 3 and b has three values. np.linalg.solve(A, b) returns the solution x = 2, y = 3, z = -1, which is unpacked into three names. Multiplying A @ solution gives b back, and np.allclose confirms it while allowing for tiny rounding errors. The matrix B has a second row that is twice the first, so the equations do not have one unique solution and solve raises LinAlgError.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Using the inverse to solve
inv(A) @ b is slower and less accurate than solve.
x = np.linalg.inv(A) @ b
x = np.linalg.solve(A, b)
Checking with ==
Floating-point results are rarely exactly equal.
print((A @ x == b).all())
print(np.allclose(A @ x, b))
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Matrix Multiplication Multiply two matrices, the operation behind every layer of a neural network. Easy
Tools for this lesson
- NumPy Matrix MultiplicationMultiply two matrices online with NumPy matmul and the @ operator.
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.