Python Program to Find Determinant of Matrix
numpy.linalg.det(matrix) or by writing a recursive function that expands by minors to calculate it manually.Examples
How to Think About It
Algorithm
Code
def determinant(matrix): size = len(matrix) if size == 1: return matrix[0][0] if size == 2: return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0] det = 0 for c in range(size): minor = [row[:c] + row[c+1:] for row in matrix[1:]] det += ((-1) ** c) * matrix[0][c] * determinant(minor) return det # Example usage matrix = [[6, 1, 1], [4, -2, 5], [2, 8, 7]] print(determinant(matrix))
Dry Run
Let's trace the determinant calculation for matrix [[1, 2], [3, 4]] through the code
Check matrix size
Matrix size is 2, so use formula ad - bc
Calculate determinant
det = 1*4 - 2*3 = 4 - 6 = -2
Return result
Return -2 as determinant
| Step | Operation | Value |
|---|---|---|
| 1 | Matrix size | 2 |
| 2 | Calculate 1*4 - 2*3 | -2 |
| 3 | Return determinant | -2 |
Why This Works
Step 1: Base cases for small matrices
For 1x1 and 2x2 matrices, the determinant is calculated directly using simple formulas to avoid unnecessary recursion.
Step 2: Recursive expansion by minors
For larger matrices, the determinant is found by expanding along the first row, calculating determinants of smaller 'minor' matrices recursively.
Step 3: Sign adjustment
Each minor's determinant is multiplied by (-1) raised to the column index to alternate signs, which is essential for correct calculation.
Alternative Approaches
import numpy as np matrix = np.array([[6, 1, 1], [4, -2, 5], [2, 8, 7]]) det = np.linalg.det(matrix) print(round(det))
import numpy as np from scipy.linalg import lu matrix = np.array([[6, 1, 1], [4, -2, 5], [2, 8, 7]]) P, L, U = lu(matrix) det = np.prod(np.diag(U)) * np.linalg.det(P) print(round(det))
Complexity: O(n!) time, O(n^2) space
Time Complexity
The recursive method expands minors for each element, leading to factorial time complexity as matrix size grows.
Space Complexity
Extra space is used to store minor matrices during recursion, roughly proportional to the square of matrix size.
Which Approach is Fastest?
Using numpy's built-in determinant function is fastest and most efficient for practical use, especially for large matrices.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive expansion | O(n!) | O(n^2) | Learning and small matrices |
| Numpy.linalg.det | O(n^3) | O(n^2) | Practical use and large matrices |
| LU decomposition | O(n^3) | O(n^2) | Efficient large matrix computations |