Python (école d'ingénieur) · Chapitre 12 · Exercice
Déterminant via la décomposition LU
Résolution de systèmes linéaires
Énoncé
Calculer le déterminant d'une matrice en utilisant sa décomposition LU.
Corrigé
import numpy as np
def determinant_lu(A):
"""
Calcule le déterminant via la décomposition LU.
"""
n = A.shape[0]
det_sign = 1
U = A.astype(float).copy()
for j in range(n - 1):
# Recherche du pivot
i_max = j
for i in range(j + 1, n):
if abs(U[i, j]) > abs(U[i_max, j]):
i_max = i
if i_max != j:
U[[j, i_max]] = U[[i_max, j]]
det_sign *= -1
if abs(U[j, j]) < 1e-15:
return 0.0
for i in range(j + 1, n):
factor = U[i, j] / U[j, j]
U[i, j:] -= factor * U[j, j:]
det = det_sign * np.prod([U[i, i] for i in range(n)])
return det
# Test sur différentes matrices
matrices = [
(np.array([[1, 2], [3, 4]]), "2x2 simple"),
(np.array([[4, 3, 2], [2, 2, 1], [3, 1, 2]]), "3x3 simple"),
(np.eye(3), "Identité"),
(2 * np.eye(3), "2×Identité")
]
for M, nom in matrices:
det_lu = determinant_lu(M)
det_np = np.linalg.det(M)
print(f"{nom:15} : LU = {det_lu:.2e}, NumPy = {det_np:.2e}")
Résultat dans la console :
2x2 simple : LU = -2.00e+00, NumPy = -2.00e+00
3x3 simple : LU = 1.00e+00, NumPy = 1.00e+00
Identité : LU = 1.00e+00, NumPy = 1.00e+00
2×Identité : LU = 8.00e+00, NumPy = 8.00e+00100 % gratuit
La suite du chapitre est sur Adloun
- 7 autres exercices corrigés dans ce chapitre, et 7 à chercher avec le tuteur
- Les 2 QCM du chapitre, le premier sans compte
- Le tuteur, qui guide pas à pas sans donner la réponse
Sans compte : le cours et le premier QCM. Exercices et tuteur : inscription gratuite en 30 secondes, sans carte bancaire.