Elimination All the Way Down

Systems of Linear EquationsHard+30 XP+30

Elimination All the Way Down

Elimination finishes at an augmented matrix like

[101013]\begin{bmatrix} 1 & 0 & 1 \\ 0 & 1 & 3 \end{bmatrix}[10​01​13​]

from which the solution x=1, y=3x = 1,\ y = 3x=1, y=3 can be read straight off. Carrying elimination all the way to a shape like that is called putting the matrix in reduced row echelon form (RREF). A matrix is in RREF when:

  1. In every row that isn't all zeros, the first nonzero entry is a 111. Call it that row's pivot.
  2. Each pivot sits further to the right than the pivot in the row above it.
  3. A pivot is the only nonzero entry in its column.
  4. Any rows of all zeros sit at the bottom.

Every matrix has exactly one RREF, and the three row operations — swap two rows, scale a row by a nonzero number, add a multiple of one row to another — are all you need to reach it.

Task: write rref(matrix). It takes a list of rows (each a list of numbers, with at least one row and one column, any shape) and returns its RREF as a new list of rows.

  • Treat any value whose absolute size is below 10−910^{-9}10−9 as zero when looking for a pivot — floating-point arithmetic leaves tiny leftovers behind.
  • Round every entry to 4 decimal places.

Once a system's augmented matrix is in RREF, the chapter's three cases are visible at a glance: a row reading [ 0  ⋯  0∣1 ][\,0 \;\cdots\; 0 \mid 1\,][0⋯0∣1] means no solution; a column of unknowns with no pivot means a free unknown and infinitely many solutions; otherwise the last column is the one and only answer.

Examples

matrix = [[2, 1, 5], [1, 3, 10]]
returns [[1.0, 0.0, 1.0], [0.0, 1.0, 3.0]]
matrix = [[1, 2, 1, 4], [2, 4, 3, 9], [3, 6, 5, 14]]
returns [[1.0, 2.0, 0.0, 3.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run