Math and Science with Python

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.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • Writing equations as A x = b
  • np.linalg.solve and checking with np.allclose
  • What happens with a singular matrix
A x = b for the three equations
2
1
-1
8
-3
-1
2
-11
-2
1
2
-3

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.

From receipts to code
A🧾 How many of each item is on each receipt
b💰 The total on each receipt
np.linalg.solve(A, b)🔍 Work out the price of each item
np.allclose(A @ x, b)✅ Check the prices add up to the totals
Quantities, totals and the unknown prices.
In one sentence

A 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

  1. Each row of A is one equation, each column one unknown.
  2. b holds the right-hand sides, in the same order as the rows.
  3. np.allclose(A @ solution, b) checks the answer while allowing for rounding.
  4. 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

Open in editor →
main.py
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)
Get a Run button for this example

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.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Using the inverse to solve

inv(A) @ b is slower and less accurate than solve.

Problem
x = np.linalg.inv(A) @ b
Fix
x = np.linalg.solve(A, b)

Checking with ==

Floating-point results are rarely exactly equal.

Problem
print((A @ x == b).all())
Fix
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.

All challenges

Tools for this lesson