Factor a matrix as PA = LU with partial pivoting and get its determinant

Why it matters LU with partial pivoting is what linear algebra libraries run underneath solve and det, and understanding it explains why some systems are unstable without pivoting.

LU factorisation is how linear systems and determinants are computed in practice. Partial pivoting swaps rows so that the pivot is the largest available entry, which keeps the arithmetic stable.

Write lu_decompose(A) for a square matrix. Return (P, L, U, det) with P a permutation matrix, L unit lower triangular and U upper triangular such that P A = L U. At column k choose the pivot row as the row r >= k with the largest |U[r, k]| (first one on ties), swap rows k and r in U, in P, and in the already-computed part of L (columns < k). If the pivot is 0, skip elimination for that column. det = (-1)^(number of actual swaps) * product of diag(U), as a float.

Signaturedef lu_decompose(A)

Example

A [[1, 2], [3, 4]] gives P [[0, 1], [1, 0]], L [[1, 0], [0.333333, 1]], U [[3, 4], [0, 0.666667]] and det -2.0.

Understand the idea

Gaussian elimination turns a matrix into an upper triangular one by subtracting multiples of rows. LU factorisation simply records those multiples in a lower triangular matrix L, so that A = L U. Once you have L and U, solving A x = b is two quick triangular solves, and the determinant is the product of U's diagonal.

Partial pivoting adds one safety rule: before eliminating a column, bring the row with the biggest entry in that column to the top. Dividing by a tiny pivot amplifies rounding errors, and a zero pivot would crash.

Worked example: A = [[1, 2], [3, 4]]. Column 0 has 1 and 3, so swap the rows: [[3, 4], [1, 2]]. The multiplier is 1/3, and row 2 becomes [1, 2] - (1/3)[3, 4] = [0, 0.667]. So L = [[1, 0], [0.333, 1]], U = [[3, 4], [0, 0.667]]. det(U) = 2, and one swap flips the sign: det(A) = -2, which matches 1 * 4 - 2 * 3.

Rule: P A = L U, det(A) = (-1)^swaps * product of diag(U).

Shapes and data flow

A (n, n) -> P, L, U (n, n), det scalar
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplelu_decompose([[1, 2], [3, 4]])
  • Sample 2: 3 by 3lu_decompose([[2, 1, 1], [4, -6, 0], [-2, 7, 2]])