mathlinear algebra
linear systems
several equations at once: elimination, and when there's one answer, none, or infinitely many.
a linear system is several equations about the same unknowns. each one is a line, or a plane, and an answer is a point on all of them. elimination subtracts multiples of one equation from the others until each unknown reads straight off, and no step changes which points are answers.
- row operations
- swap · scale by c ≠ 0 · add a multiple each one can be undone, so the answers stay the same
- one answer
- det A ≠ 0 a pivot in every column. two lines crossing once
- none
- 0 = c, c ≠ 0 a row of zeros with a nonzero right-hand side. parallel lines
- infinitely many
- 0 = 0 a column with no pivot is a free unknown. the same line twice
- pivot
- the number you divide by take the biggest in its column. a tiny one blows rounding error up
- solve, don't invert
- x from Ax = b, not A⁻¹b A⁻¹ is n solves in one, plus a multiply, for the same x
- unknowns tied together: two prices from two receipts, three currents from three loops
- fitting a line through points, where the best fit is the answer to a small system
- the matrices page, where a system is Ax = b and the determinant says if there's one answer
- eigenvectors, where (A − λI)x = 0 is a system that has to have infinitely many answers
on this page
the idea
one equation in two unknowns, , has endless answers: , , , every point of a line. a second equation, , is another line. a pair that fits both is a point on both lines: where they cross. two equations, two unknowns, and in the usual case one answer.
finding it is elimination. the second equation, minus three copies of the first, has no left:
then the first equation gives . the crossing is . the movie does the same thing on the augmented matrix, the equations with their words stripped off: coefficients on the left of the bar, right-hand sides on the right. watch the lines: each row operation turns one of them, and the crossing never moves.
an animation on a plot from x = −2 to 5 and y = −1 to 4, with the augmented matrix beside it. the lines x + 2y = 5 in cyan and 3x − y = 1 in amber cross at (1, 2). row operation R2 − 3·R1 turns the amber line about the crossing until it is horizontal, y = 2, and the matrix's second row goes from 3 −1 | 1 to 0 −7 | −14; halfway through, the row reads 1.5x − 4y = −6.5 and still passes through (1, 2). dividing row 2 by −7 changes its numbers to 0 1 | 2 and leaves the line where it is. then R1 − 2·R2 turns the cyan line about the crossing until it is vertical, x = 1, and the matrix reads 1 0 | 1; 0 1 | 2. the original two lines stay behind, dashed, and the point (1, 2) never moves.
the matrices page writes the same system as one equation, , with the block of coefficients. the vectors page is where and come from.
explore
two lines, and , from six sliders. the readout gives both equations, the determinant , and the answer: the one crossing, or why there isn’t one.
- line 1
- x + 2y = 5
- line 2
- 3x − y = 1
- determinant a₁b₂ − a₂b₁
- −7
- answer
- x = 1, y = 2
a plot from x = −6 to 6 and y = −4 to 4 with two lines, a₁x + b₁y = c₁ in cyan and a₂x + b₂y = c₂ in amber, each from three sliders: a and b from −4 to 4, c from −8 to 8, whole numbers. buttons set three starting systems. it opens on x + 2y = 5 and 3x − y = 1: determinant −7, the one answer x = 1, y = 2, marked on the plot. the second preset is x + 2y = 5 and 2x + 4y = 4: determinant 0, no answer, parallel lines. the third is x + 2y = 5 and 2x + 4y = 10: determinant 0, infinitely many, the same line twice, drawn dashed over itself. the readout gives both equations, the determinant and the answer, as fractions when the crossing is off the grid.
- the determinant is exactly when the second line’s direction is a multiple of the first’s. then the lines are parallel, and never meet, or they are the same line, and meet everywhere
- a row like is no line at all: holds nowhere, so the system has no answer. holds everywhere, and the other line is the whole answer
- the crossing is a fraction more often than not. and meet at
try it
x + 2y = 5 and 2x + 4y = 4. how many answers?
pick one.
a practice exercise with four kinds of question: say whether a system of two equations has one answer, none or infinitely many, pick the point that is on both of two lines, name the row operation that clears x from the second row, and say which row partial pivoting brings to the top. once there is a pick, a question about two lines draws them. it opens on x + 2y = 5 and 2x + 4y = 4, which has no answer, then x + y = 3 and x − y = 1, which meet at (2, 1).
the rules
a linear equation is a line, or a plane
an equation is linear when each unknown appears on its own, multiplied by a number: , with no , no , no . in two unknowns its answers make a line, and in three, , a plane. a linear system is several of these about the same unknowns, and a solution is a point that fits every one.
one, none, or infinitely many
a linear system has exactly one answer, no answer, or infinitely many. never two, never seven.
why: suppose and are both answers to . then for any ,
so every point on the line through and is an answer too. two answers force infinitely many. for two lines in a plane, that is the picture from the explore figure: they cross once, run parallel, or are the same line.
row operations
three moves on the rows of the augmented matrix, each one a move on the equations:
- swap two rows: the same equations in a different order
- scale a row by a number : both sides of one equation times
- add a multiple of one row to another:
each can be undone by a move of the same kind: swap back, scale by , add . that is why the answers never change, and it is why is not allowed: a row times is , and nothing brings the equation back.
elimination
forward elimination takes the matrix to row echelon form: each row’s first nonzero entry, its pivot, sits to the right of the pivot above it, and the rows below a pivot have zeros under it. column by column: pick the pivot row, swap it up, and add multiples of it to the rows below to clear the column.
back substitution then reads the answer off, bottom row first. the last pivot row has one unknown left, the one above it has two with one already known, and so on up.
the echelon form also says how many answers there are:
- a row with reads : no answer
- a column with no pivot is a free unknown: it can be anything, the others follow from it, and there are infinitely many answers (unless a row says there are none)
- a pivot in every column, and no row: one answer
as Ax = b
the system is , with the coefficients, the unknowns and the right-hand sides. for the movie’s system:
there is exactly one answer for every when , which is when has an inverse: then . the matrices page is where the determinant comes from. for it is , and the answer is cramer’s rule:
with , and .
is the right formula and the wrong program. to build you solve systems at once, one for each column of the identity, and then there is still the multiply by . counting multiplications and divisions, one solve of a system by elimination and back substitution takes , against to invert that way and multiply. at it is against , close to for the solve and almost four times that for the inverse. every extra operation is another rounding, so the inverse is slower and less accurate for the same . numpy’s solve hands the system to lapack’s gesv,1 which factors by elimination with partial pivoting and solves from the factors.2
partial pivoting
when a column has several candidates for the pivot, take the one with the biggest absolute value and swap its row up. clearing the column below multiplies the pivot row by for each row , and a tiny pivot makes huge. the row below becomes , and when is times the size of , every digit had is lost in the subtraction. with the biggest entry as the pivot, , and the rows keep their digits. the worked example below has the numbers.
three unknowns: planes
with three unknowns each equation is a plane, and the same three outcomes appear. three planes meet at one point, like two walls and a floor; or along a line, like the pages of an open book; or nowhere, when two are parallel, or when each pair meets but the three lines of meeting run side by side, like a triangular prism. elimination tells them apart by the echelon form, and the stepper below runs all three.
worked examples
two equations, by hand
and , as the movie did it:
that is row echelon form, and row 2 says . back substitution: , so . the movie went one step further, , to make the left block the identity: that is reduced row echelon form, and the answer is then the right-hand column.
three equations, step by step
the stepper runs elimination with partial pivoting on three systems that share two rows. only the middle row differs, and that is enough to give one answer, none, or infinitely many.
- R1 4x + 2y − 2z = 6
- R2 2x + 3y + z = 9
- R3 −2x + y + 4z = 4
3 equations, 3 unknowns. the coefficients sit left of the bar, the right-hand sides to its right.
step 1 of 12
eliminate(M): # M is the augmented matrix [A | b] r = 0 # the next pivot row for each column c of A: p = the row at or below r with the biggest |M[p][c]| if M[p][c] == 0: continue # no pivot here: a free variable swap rows r and p for each row i below r: M[i] -= (M[i][c] / M[r][c]) * M[r] # clears column c in row i r += 1 return M # row echelon form back_substitute(M): if a row reads 0 ... 0 | c with c != 0: no answer if a column has no pivot: infinitely many, that unknown is free for each pivot row, bottom up: x[c] = (rhs - the terms already known) / pivot return xa stepper over a 3 × 4 augmented matrix with the pseudocode beside it, for one of three systems. all three have rows 4 2 −2 | 6 and −2 1 4 | 4, and differ in the middle row. with 2 3 1 | 9: the pivot 4 is already on top, R2 − 1/2·R1 and R3 + 1/2·R1 clear column 1, the pivot 2 needs no swap, R3 − R2 clears column 2, and the echelon form 4 2 −2 | 6; 0 2 2 | 6; 0 0 1 | 1 has pivots 4, 2, 1. back substitution gives z = 1, y = 2, x = 1. with 2 1 −1 | 4: R2 − 1/2·R1 leaves 0 0 0 | 1, a swap brings 0 2 3 | 7 up, and the last row reads 0 = 1, so there is no answer. with 2 1 −1 | 3: the same steps leave 0 0 0 | 0, z is free, y = (7 − 3t)/2 and x = (5t − 1)/4, a line of answers; t = 1 gives (1, 2, 1). the row being changed is white, the row it reads from cyan, and the pivot ringed in amber.
for the first system, back substitution reads: row 3, . row 2, , so . row 1, , so . the answer is , and putting it back into the three original equations checks it: , , .
a tiny pivot
and . the answer is to twenty digits: from the second equation , and the first then says up to a term of size . in doubles, with the rows as they come, the pivot is and the multiplier is , so reads
a double carries 53 bits, about 16 decimal digits,3 so the and the vanish next to and both sides round to the same number. exactly, and then . wrong by a whole unit. with the swap, the pivot is , the multiplier is , and reads , where both sides round to : , . the same rounding, to the same digit, and this time it lands on the answer.
the key idea up close
why a row operation never changes the answers
call the old system and the new one , after . take any point that solves . it makes row 1 true, , and row 2 true, . the new row 2 is , and at its left side is
the new right side. so solves too: every answer of is an answer of .
now the other direction. comes from by the same kind of move, , so the argument runs again and every answer of is an answer of . the two systems have exactly the same answers. a swap and a scale by undo the same way, so the same holds for them.
the movie shows it: as runs from to , every in-between system is a legitimate row operation away from the original, so every in-between amber line passes through . the line turns, the crossing stays.
a scale by breaks the second half. the new row is true everywhere, so every old answer is still an answer, but there is no move back, and the new system can have more answers than the old. scale row 2 of the movie’s system by and what is left is alone: a whole line of answers where there was one.
in code
elimination with partial pivoting and back substitution, saying when there is one answer, none, or infinitely many. it runs on fractions.Fraction for the exact examples above, with tol=0, and on floats for the two rounding points. an entry smaller than tol times the biggest entry in the matrix counts as zero, so a pivot that rounding left at is not divided by.
"""gaussian elimination with partial pivoting and back substitution, saying when a system has one answer, none, or infinitely many. it works on fractions.Fraction for exact small examples and on floats for the two rounding points the page makes: a pivot of 1e-20 gives x = 0 instead of 1 unless the rows are swapped first, and a pivot that should be 0 can come out as 4.4e-16, which only a tolerance catches. run the file to print both."""
from __future__ import annotations
from fractions import Fraction
from typing import NamedTuple
Number = float | Fraction
Matrix = list[list[Number]]
class Solution(NamedTuple):
"""How many answers, and which: `kind` is "one", "none" or "many". `values` holds the one answer, or one
answer among the many with every free unknown set to 0. `free` lists the free unknowns' columns."""
kind: str
values: list[Number] | None
free: list[int]
def augment(a: list[list[Number]], b: list[Number]) -> Matrix:
"""Return [A | b]: each row of A with its right-hand side appended."""
return [list(row) + [rhs] for row, rhs in zip(a, b, strict=True)]
def eliminate(m: Matrix, pivoting: bool = True, tol: float = 1e-12) -> tuple[Matrix, list[tuple[int, int]]]:
"""Return the row echelon form of the augmented matrix and its pivot positions, by row operations on a copy.
For each column, the row at or below the next pivot row with the biggest entry comes up (partial pivoting),
and multiples of it clear the column below. With `pivoting` off, rows are swapped only past a zero pivot. An
entry within `tol` times the biggest entry of the original matrix counts as 0, so a pivot that rounding left
at 1e-16 is not divided by. With Fractions, pass tol=0 for an exact zero test.
"""
m = [list(row) for row in m]
rows, cols = len(m), len(m[0]) - 1
scale = max((abs(v) for row in m for v in row[:cols]), default=0) or 1
zero = lambda v: abs(v) <= tol * scale # noqa: E731
pivots: list[tuple[int, int]] = []
r = 0
for c in range(cols):
if r == rows:
break
if pivoting:
p = max(range(r, rows), key=lambda i: abs(m[i][c]))
else:
p = next((i for i in range(r, rows) if not zero(m[i][c])), r)
if zero(m[p][c]):
continue
m[r], m[p] = m[p], m[r]
for i in range(r + 1, rows):
k = m[i][c] / m[r][c]
m[i] = [v - k * w for v, w in zip(m[i], m[r], strict=True)]
m[i][c] = 0 * m[i][c] # exactly 0, in the row's own number type
pivots.append((r, c))
r += 1
return m, pivots
def back_substitute(m: Matrix, pivots: list[tuple[int, int]], tol: float = 1e-12) -> Solution:
"""Read the answer off a row echelon form.
A row of zeros with a nonzero right-hand side means no answer. A column without a pivot is a free unknown,
so there are infinitely many; the one returned sets every free unknown to 0. Otherwise the pivot unknowns
come out bottom row up.
"""
cols = len(m[0]) - 1
scale = max((abs(v) for row in m for v in row), default=0) or 1
for row in m:
if all(abs(v) <= tol * scale for v in row[:cols]) and abs(row[cols]) > tol * scale:
return Solution("none", None, [])
pivot_cols = {c for _, c in pivots}
free = [c for c in range(cols) if c not in pivot_cols]
values: list[Number] = [0 * m[0][0]] * cols
for r, c in reversed(pivots):
rhs = m[r][cols]
for j in range(c + 1, cols):
rhs = rhs - m[r][j] * values[j]
values[c] = rhs / m[r][c]
return Solution("many" if free else "one", values, free)
def solve(a: list[list[Number]], b: list[Number], pivoting: bool = True, tol: float = 1e-12) -> Solution:
"""Solve A x = b by elimination and back substitution."""
m, pivots = eliminate(augment(a, b), pivoting, tol)
return back_substitute(m, pivots, tol)
def main() -> None:
"""Print the two rounding points: the tiny pivot with and without a swap, and the zero that isn't one."""
eps = 1e-20
a = [[eps, 1.0], [1.0, 1.0]]
b = [1.0, 2.0]
print(f"{eps:g}x + y = 1 and x + y = 2: the answer is x = y = 1 to 20 digits")
for pivoting in (False, True):
s = solve(a, b, pivoting=pivoting, tol=0)
print(f" {'with' if pivoting else 'without'} the swap: x = {s.values[0]}, y = {s.values[1]}")
a = [[0.1, 0.7], [0.3, 2.1]]
b = [0.8, 2.4]
print("0.1x + 0.7y = 0.8 and 0.3x + 2.1y = 2.4: the same line twice, so infinitely many")
for pivoting in (False, True):
m, _ = eliminate(augment(a, b), pivoting=pivoting, tol=0)
s = solve(a, b, pivoting=pivoting, tol=0)
print(f" {'with' if pivoting else 'without'} the swap, tol = 0: the second pivot is {m[1][1]}, so {s.kind}: {s.values}")
s = solve(a, b)
print(f" tol = 1e-12: {s.kind}, y is free")
if __name__ == "__main__":
main()the run first does the tiny pivot above: without the swap, and ; with it, and . then it takes and , the same line written twice, so infinitely many answers. by hand, is a row of zeros. in doubles, and are not the decimals they look like, only the closest fractions with a power of two below,3 and comes out as . then is , not . with tol=0 the code takes that as a pivot, divides by it, and reports one answer, : a point on the line, offered as the only one. the swap doesn’t help, since the pivot then comes out as and the report is the same. with the default tol=1e-12 both count as the zero they should be, and the answer is infinitely many, free.
pitfalls
- dividing by a tiny pivot. the multiplier is the entry over the pivot, so a pivot of turns the next row into copies of the pivot row and the row’s own digits are gone. swap the biggest entry up first. without the swap the example above gets instead of
- assuming there’s exactly one answer. happens, and it means parallel lines or the same line twice. before dividing by a determinant or a pivot, check it isn’t zero, and read a row as “no answer”, not as a bug
- a “zero” pivot that is really . rounding rarely gives an exact zero: is . test against a tolerance relative to the matrix’s biggest entry, or a system with infinitely many answers reports one, and a system with none reports one too
- inverting a matrix to solve one system. is solves and a multiply where one solve would do, and every extra operation rounds. operations against for . call
solve, notinv - multiplying a row by 0. it’s not a row operation. the row becomes , the equation is gone, and the system picks up answers it never had. scaling by is fine
- forgetting the right-hand side. a row operation acts on the whole row, bar included. on the coefficients alone changes which points are answers
- swapping only on an exact zero. a pivot of isn’t zero, so a rule of “swap when the pivot is 0” leaves it in place. partial pivoting swaps whenever something below is bigger
practice
-
how many answers does each system have? and . then and . then and .
answer
the first: the determinant is , so one answer, and it is . the second: the determinant is , and row 2’s left side is twice row 1’s while : parallel lines, no answer. the third: row 2 is exactly twice row 1, right-hand side included: the same line, infinitely many answers.
-
solve and by elimination.
answer
swap so the pivot is : on top. then : , so and . back up: , so . check: and .
-
: . : . which row operation clears the from , what does become, and what is the answer?
answer
, so : , which is , so . then gives and . check in : .
-
solve , , .
answer
gives and gives :
swap rows 2 and 3 so the pivot is , then : , so and . back up: gives , and gives . the answer is . check: , , .
-
and . for which is there no answer? is there a with infinitely many? and solve it for .
answer
the determinant is . it is only at , where row 2’s left side is three times row 1’s but : parallel lines, no answer. no gives infinitely many, since that would need the right-hand side to be as well. every other gives one answer. at the determinant is , and cramer’s rule gives and . check: and .
-
and , in doubles. say what elimination without a swap computes for and for , and why, and what it computes with the swap.
answer
without the swap the multiplier is , and reads . a double holds about 16 digits, so both and round to , and exactly. then , off by a whole unit from the true . with the swap the pivot is and the multiplier : , both sides round to , , and .
sources
-
numpy’s numpy.linalg.solve (opens in a new tab) docs: the solutions are computed with the lapack routine
_gesv, and the matrix must be square and of full rank. ↩ -
lapack’s dgesv (opens in a new tab) source: it computes the solution of a real system A · X = B by factoring A as P · L · U with an lu decomposition with partial pivoting and row interchanges, then solving from the factored form. ↩
-
python’s tutorial, floating-point arithmetic: issues and limitations (opens in a new tab): almost all platforms map python floats to ieee 754 binary64 doubles, which carry 53 bits of precision, and a decimal like 0.1 is stored as the closest fraction of the form j / 2ⁿ, which for 0.1 is a little above a tenth. ↩ ↩2