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
Découvrez Solve a System of Linear Equations with NumPy avec un exemple pratique modifiable et exécutable en ligne.
Points clés
- 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.
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
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)
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.
- 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.
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éfisOutils pour cette leçon
- Multiplier des matrices avec NumPyDans cette leçon, vous allez multiplier deux matrices avec l'opérateur @ de NumPy et le distinguer de la multiplication terme à terme.
- Traceur de courbes en ligne : tracer des points et des fonctionsTracez des points, un tableau collé ou des fonctions comme sin(x) en ligne et téléchargez le graphique en PNG. Traceur gratuit qui vous donne aussi le code Python avec Matplotlib.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.