Application: Cramer's Rule
Cramer's rule writes the solution of a square linear system as ratios of determinants, one variable at a time. It is elegant, it gives closed-form formulas for small and symbolic systems (including a famous ray–triangle test in graphics), and it is a terrible general-purpose solver: with cofactor expansion its cost grows like , against for elimination. This lesson shows all three sides and times the difference.
The rule
Let be an invertible matrix. For each , let be with column replaced by . Then the unique solution of is
example. Solve , :
Proof. Let be the identity matrix with column replaced by . Then has columns , which are the columns of with column replaced by : . Expanding along row gives . So by multiplicativity (Properties of Determinants), . ∎
Equivalently, Cramer's rule is the inverse formula (Application: A Formula for the Inverse) written out entry by entry.
from sympy import Matrix, symbols, simplify
def cramer(A, b):
d = A.det()
xs = []
for i in range(A.cols):
Ai = A.copy()
Ai[:, i] = b # replace column i by b
xs.append(Ai.det() / d)
return xs
A = Matrix([[2, 1, -1], [1, 3, 2], [3, -1, 4]])
b = Matrix([1, 13, 13])
print("Cramer:", cramer(A, b), " solve:", list(A.solve(b)))
# symbolic: a general 2x2 system
a11, a12, a21, a22, b1, b2 = symbols("a11 a12 a21 a22 b1 b2")
x, y = cramer(Matrix([[a11, a12], [a21, a22]]), Matrix([b1, b2]))
print("x =", simplify(x))Cramer: [1, 2, 3] solve: [1, 2, 3]
x = (-a12*b2 + a22*b1)/(a11*a22 - a12*a21)
The symbolic answer is a closed formula: . Such formulas show, for example, that the solution of an integer system is a fraction with denominator , and how the solution changes when one coefficient changes.
Why it is slow: versus
Cramer's rule needs determinants of size . With cofactor expansion (Minors and Cofactors) each costs on the order of multiplications (about ), so the whole rule is on the order of . Gaussian elimination needs about operations. Count and time both on the same systems:
import time
import numpy as np
mults = 0
def det_cofactor(M):
global mults
n = len(M)
if n == 1:
return M[0][0]
total = 0.0
for j in range(n):
minor = [row[:j] + row[j + 1:] for row in M[1:]]
mults += 1
total += (-1) ** j * M[0][j] * det_cofactor(minor)
return total
def cramer_cofactor(A, b):
d = det_cofactor(A)
return [det_cofactor([row[:i] + [bi] + row[i + 1:] for row, bi in zip(A, b)]) / d
for i in range(len(A))]
rng = np.random.default_rng(1)
for n in (3, 5, 7, 8):
A = rng.normal(size=(n, n)); b = rng.normal(size=n)
mults = 0
t0 = time.perf_counter(); x1 = cramer_cofactor(A.tolist(), b.tolist()); t1 = time.perf_counter()
x2 = np.linalg.solve(A, b); t2 = time.perf_counter()
print(f"n = {n}: Cramer mults = {mults:6d} elimination ~ {round(2 * n**3 / 3):3d} flops "
f"same answer: {np.allclose(x1, x2)}")
print("n = 8: np.linalg.solve faster than Cramer:", (t2 - t1) < (t1 - t0))n = 3: Cramer mults = 36 elimination ~ 18 flops same answer: True
n = 5: Cramer mults = 1230 elimination ~ 83 flops same answer: True
n = 7: Cramer mults = 69272 elimination ~ 229 flops same answer: True
n = 8: Cramer mults = 623520 elimination ~ 341 flops same answer: True
n = 8: np.linalg.solve faster than Cramer: True
The multiplication count grows by a factor of about at every step; elimination barely moves. Extrapolating: for , Cramer with cofactor expansion would need more than multiplications (years of CPU time), while np.linalg.solve handles a system in microseconds and a one in well under a second.
Even computing each determinant by elimination () leaves Cramer at , still times slower than solving once. And numerically, ratios of determinants are less stable than LU with pivoting.
Where Cramer's rule is the right tool
- Tiny systems in hot loops. For and systems, Cramer's closed form is branch-free and fast. The classic Möller–Trumbore ray–triangle intersection solves the system exactly this way, with the determinants written as cross and dot products (scalar triple products) (Ray–Triangle).
- Line intersection in 2D: two lines and meet at Cramer's formulas, and signals parallel lines, a test every 2D geometry library contains.
- Symbolic work and proofs: it shows the solution is a rational function of the coefficients, which is used for sensitivity analysis and in theory (for example, integer systems with have integer solutions).
Exercises
Exercise 1: A system
Solve , with Cramer's rule.
Answer
, .
Solution
Exercise 2: One unknown of a system
Find only in the system , , .
Answer
.
Solution
Check with code:
from sympy import Matrix
A = Matrix([[1, 1, 1], [2, -1, 3], [1, 2, -1]])
b = Matrix([6, 13, 2])
A3 = A.copy(); A3[:, 2] = b
print(A.det(), A3.det(), A3.det() / A.det(), list(A.solve(b)))5 11 11/5 [17/5, 2/5, 11/5]
The full solution is , , ; Cramer's rule gave without computing the other two.
Exercise 3: Intersect two lines
Use Cramer's rule to intersect and . Then explain what would mean geometrically.
Answer
. means the lines are parallel (or the same line).
Solution
means the normal vectors and are parallel, so the lines are parallel: no intersection, or infinitely many if they coincide.
Exercise 4: Estimate the cost
Using the rough estimate for Cramer with cofactor expansion, estimate the multiplications for and compare with .
Answer
About versus 1152.
Solution
from math import factorial
n = 12
print(f"{(n + 1) * factorial(n):.2e}", round(2 * n**3 / 3))6.23e+09 1152
Billions of multiplications against about a thousand, a ratio of more than five million.
Test yourself
In Cramer's rule, how is formed?
- Replace row 2 of with
- Multiply column 2 by
- Delete row and column 2
- Replace column 2 of with
Why is Cramer's rule with cofactor expansion unsuitable for a system?
- It gives wrong answers
- It only works for symmetric matrices
- Its cost grows like , astronomically more than elimination's
- It needs complex numbers
Where is Cramer's rule genuinely used in practice?
- Training large neural networks
- Small fixed-size systems such as ray–triangle intersection
- Solving sparse systems
- Never