Math and Science with Python

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.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • np.linalg.inv and the identity matrix
  • Why the determinant must not be 0
  • Why np.linalg.solve beats inv(A) @ b
A = [[4, 7], [2, 6]]
inv(A)
  • [[0.6, -0.7]
  • [-0.2, 0.4]]
A @ inv(A)
  • [[1, 0]
  • [0, 1]]
det(A)
  • 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

  1. np.linalg.inv(A) returns the inverse as a new array.
  2. A @ A_inv should be the identity np.eye(2); compare with np.allclose.
  3. np.linalg.det(A) is 10 here; a determinant of 0 means no inverse.
  4. np.linalg.solve(A, b) gives the same answer as inv(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

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

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.

  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