Lesson 8 of 18
Determinant
The Determinant
The determinant of a square matrix is a single number that encodes how the matrix scales area (2D) or volume (3D).
For a matrix:
detegin{pmatrix} a & b \ c & d end{pmatrix} = ad - bc
def det(A):
if len(A) == 1:
return A[0][0]
if len(A) == 2:
return A[0][0]*A[1][1] - A[0][1]*A[1][0]
# Cofactor expansion along first row
return sum(
((-1)**j) * A[0][j] * det([[A[i][k] for k in range(len(A)) if k != j]
for i in range(1, len(A))])
for j in range(len(A))
)
A = [[3, 0], [0, 2]]
print(int(round(det(A)))) # 6 — scales area by 6
What the Determinant Tells You
| Meaning | |
|---|---|
| Matrix is singular — no inverse exists, squishes space to a lower dimension | |
| Preserves orientation | |
| Flips orientation | |
| Preserves area/volume |
Singular Matrices
If rows are linearly dependent (one row is a multiple of another), the determinant is 0:
S = [[1, 2], [2, 4]] # row 2 = 2 × row 1
print(int(round(det(S)))) # 0
Your Task
Implement det(A) that returns the determinant as an integer (rounded).
Pyodide loading...
Loading...
Click "Run" to execute your code.