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.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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

Découvrez Solve a System of Linear Equations with NumPy avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  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.

Quand l’utiliser ?

  • Solve equations, integrals and differential equations in a few lines.
  • Fit models to measured data and analyse signals in science and engineering classes.
  • Check homework answers numerically and see where a hand calculation went wrong.

Code d’exemple

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)
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

x = 2.0000, y = 3.0000, z = -1.0000
A @ solution = [8.0, -11.0, -3.0]
Correct: True
Singular matrix: Singular matrix

Explication du code

Cet exemple montre Solve a System of Linear Equations with NumPy en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  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.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis

Outils pour cette leçon