Matrix Inverse in Python with numpy.linalg.inv
Find the inverse of a square matrix with np.linalg.inv, check it against the identity, and learn when not to use it.
- np.linalg.inv and the identity matrix
- Why the determinant must not be 0
- Why np.linalg.solve beats inv(A) @ b
- [[0.6, -0.7]
- [-0.2, 0.4]]
- [[1, 0]
- [0, 1]]
- 10
- not 0, so A has an inverse
Undoing a matrix
Découvrez Matrix Inverse in Python with NumPy avec un exemple pratique modifiable et exécutable en ligne.
Points clés
np.linalg.inv(A)returns the inverse as a new array.A @ A_invshould be the identitynp.eye(2); compare withnp.allclose.np.linalg.det(A)is 10 here; a determinant of 0 means no inverse.np.linalg.solve(A, b)gives the same answer asinv(A) @ b, faster and more accurately.
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
A = np.array([[4, 7],
[2, 6]], dtype=float)
A_inv = np.linalg.inv(A)
print("Inverse:")
print(A_inv.round(4))
# A matrix times its inverse gives the identity matrix
identity = A @ A_inv
print("A @ A_inv:")
print(identity.round(10) + 0.0) # + 0.0 turns -0.0 into 0.0
print("Is identity:", np.allclose(identity, np.eye(2)))
# The determinant must not be 0
print(f"Determinant: {np.linalg.det(A):.4f}")
# To solve A x = b, prefer np.linalg.solve over inv(A) @ b
b = np.array([1, 2], dtype=float)
print("inv(A) @ b:", (A_inv @ b).round(4).tolist())
print("solve(A, b):", np.linalg.solve(A, b).round(4).tolist())
Résultat de l’exécution
Inverse:
[[ 0.6 -0.7]
[-0.2 0.4]]
A @ A_inv:
[[1. 0.]
[0. 1.]]
Is identity: True
Determinant: 10.0000
inv(A) @ b: [-0.8, 0.6]
solve(A, b): [-0.8, 0.6]
Explication du code
Cet exemple montre Matrix Inverse in Python 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.