Gaussian Elimination
Gaussian elimination is the systematic way to apply elementary row operations until a system is in echelon form, a staircase shape that can be solved from the bottom up. It decides whether a system has zero, one or infinitely many solutions, and in this lesson you implement it yourself.
Echelon form
A matrix is in row echelon form when:
- all zero rows are at the bottom, and
- the first non-zero entry of each row (its pivot, or leading entry) is strictly to the right of the pivot in the row above.
The columns that contain a pivot are pivot columns; their variables are pivot variables (or leading variables). The other variables are free.
The algorithm
Work column by column, from left to right:
- Find a row, at or below the current row, with a non-zero entry in this column. If there is none, move on to the next column (this variable will be free).
- Swap that row into the current position. Its entry is the pivot.
- For every row below, add a multiple of the pivot row that makes the entry under the pivot 0: .
- Move one row down and one column right, and repeat.
Then read off the result:
- A row with says : the system is inconsistent.
- Otherwise it is consistent. If every variable column has a pivot, the solution is unique; if some variable is free, there are infinitely many solutions.
- Solve by back substitution: the last equation first, then work upwards.
A worked example
Implementing it with Fractions
from fractions import Fraction as F
def echelon(M):
"""Forward elimination. Returns (echelon matrix, list of pivot columns)."""
M = [[F(a) for a in row] for row in M]
rows, cols = len(M), len(M[0]) - 1 # last column is the right-hand side
pivots, r = [], 0
for c in range(cols):
p = next((i for i in range(r, rows) if M[i][c] != 0), None)
if p is None:
continue # no pivot here: free variable
M[r], M[p] = M[p], M[r]
for i in range(r + 1, rows):
f = M[i][c] / M[r][c]
M[i] = [a - f * b for a, b in zip(M[i], M[r])]
pivots.append(c)
r += 1
if r == rows:
break
return M, pivots
def back_substitute(M, pivots):
n = len(M[0]) - 1
if any(all(a == 0 for a in row[:-1]) and row[-1] != 0 for row in M):
return "inconsistent"
if len(pivots) < n:
return "infinitely many solutions"
x = [F(0)] * n
for r in reversed(range(n)):
s = sum(M[r][j] * x[j] for j in range(r + 1, n))
x[r] = (M[r][-1] - s) / M[r][r]
return x
A = [[1, 2, 1, 4], [2, 5, 3, 11], [-1, 1, 4, 10]]
E, piv = echelon(A)
for row in E:
print([str(a) for a in row])
print("pivot columns:", piv)
print("solution:", [str(v) for v in back_substitute(E, piv)])['1', '2', '1', '4']
['0', '1', '1', '3']
['0', '0', '2', '5']
pivot columns: [0, 1, 2]
solution: ['1/2', '1/2', '5/2']
The code takes the first non-zero entry as pivot. That is fine with exact fractions; with floating point you would pick the entry of largest absolute value instead (partial pivoting), which keeps rounding errors small.
Comparing with SymPy
SymPy gives the same answer. Its echelon_form() may scale rows differently, since echelon form is not unique (only the reduced form is, see Uniqueness of the Reduced Echelon Form), but the pivot positions and the solution agree:
from sympy import Matrix
aug = Matrix([[1, 2, 1, 4], [2, 5, 3, 11], [-1, 1, 4, 10]])
print(aug.echelon_form().tolist())
print("solution:", list(aug[:, :3].solve(aug[:, 3])))
# an inconsistent system: the last row becomes 0 0 0 | nonzero
bad = Matrix([[1, 1, 2, 3], [2, 3, 1, 5], [3, 4, 3, 9]])
print(bad.echelon_form().tolist())[[1, 2, 1, 4], [0, 1, 1, 3], [0, 0, 2, 5]]
solution: [1/2, 1/2, 5/2]
[[1, 1, 2, 3], [0, 1, -3, -1], [0, 0, 0, 1]]
In the second system on the left-hand side, but on the right, so elimination produces .
In software
Gaussian elimination costs about arithmetic operations for equations. That cubic growth is why big problems (millions of unknowns in physics simulations or finite element models) use sparse or iterative methods instead. For dense matrices, numpy.linalg.solve calls LAPACK's LU factorization with partial pivoting, which is Gaussian elimination with bookkeeping. See Numerical Linear Algebra.
Exercises
Exercise 1: Echelon or not?
Which are in row echelon form? (a) (b) (c) .
Answer
Only (a).
Solution
(b) the pivot of row 2 (column 1) is left of the pivot of row 1 (column 2). (c) has a zero row above a non-zero row.
Exercise 2: Eliminate by hand
Solve , , by Gaussian elimination.
Answer
, , .
Solution
from sympy import Matrix
print(list(Matrix([[1, -1, 1], [2, 1, -1], [1, 2, 3]]).solve(Matrix([2, 1, 14]))))[1, 2, 3]
Exercise 3: Inconsistent or infinite?
Run elimination on , . For which is the system consistent, and how many solutions does it then have?
Answer
Consistent only for , with infinitely many solutions ( free, ).
Solution
Exercise 4: A free variable (code)
Run the lesson's echelon function on , (two equations, three unknowns). Which column has no pivot?
Answer
Pivots in columns 0 and 2; column 1 () is free.
Solution
, so the second pivot jumps to the column. Then and with free.
from fractions import Fraction as F
def echelon(M):
M = [[F(a) for a in row] for row in M]
rows, cols = len(M), len(M[0]) - 1
pivots, r = [], 0
for c in range(cols):
p = next((i for i in range(r, rows) if M[i][c] != 0), None)
if p is None:
continue
M[r], M[p] = M[p], M[r]
for i in range(r + 1, rows):
f = M[i][c] / M[r][c]
M[i] = [a - f * b for a, b in zip(M[i], M[r])]
pivots.append(c); r += 1
if r == rows:
break
return M, pivots
E, piv = echelon([[1, 1, 1, 6], [2, 2, 3, 14]])
print([[str(a) for a in row] for row in E], piv)[['1', '1', '1', '6'], ['0', '0', '1', '2']] [0, 2]
Test yourself
After elimination, a row reads . What does that mean?
- The system is inconsistent
- There are infinitely many solutions
- The row can be deleted
A consistent system with 4 unknowns has 3 pivots after elimination. How many solutions?
- None
- Exactly one
- Exactly three
- Infinitely many
Why do floating-point implementations choose the largest available entry as the pivot?
- It is required for correctness with exact numbers
- It reduces the growth of rounding errors
- It makes the matrix symmetric
- It avoids back substitution