Orthogonal matrices, Gram-Schmidt and QR factorization
Orthonormal bases simplify difficult problems and orthogonal matrices preserve geometry. Construct QR using classical and modified Gram–Schmidt and Householder reflections, measure how well each preserves orthogonality, and solve least squares without squaring the condition number.
After this lesson you can
- Prove that orthogonal matrices preserve norms, angles and volumes and classify them as rotations or reflections.
- Construct QR factorizations using classical Gram–Schmidt, modified Gram–Schmidt and Householder reflections.
- Measure and explain each method's loss of orthogonality as conditioning changes.
- Solve least squares using QR and compare its accuracy with normal equations.
- Use Givens rotations to zero specific entries.
Before you start
Motivation: the basis that makes everything easy
In the inner-products lesson you saw that an orthonormal basis turns coordinate problems into dot products. Put it in the columns of a matrix and three problems that generally require solving a linear system become trivial:
- Coordinates. In an arbitrary basis, finding with requires solving a system. In an orthonormal basis, , i.e. : one multiplication.
- Projections. The projection matrix onto is . If columns are orthonormal, and the formula reduces to .
- Least squares. The normal equations become .
A second reason is less visible and more important in practice: matrices with orthonormal columns amplify nothing. Multiplication by preserves lengths, so it does not enlarge rounding errors already in the vector. This is why the most reliable dense numerical linear-algebra algorithms (QR, the QR eigenvalue algorithm, SVD) chain orthogonal transformations, and why they appear throughout the curriculum:
- Transformers. RoPE (rotary position embedding) rotates queries and keys using blockwise rotations; since the dot product of two rotated vectors depends only on the difference of rotation angles, attention sees only relative positions.
- Network initialization. A linear layer with orthogonal weights preserves input norm; orthogonal initialization prevents signals from exploding or vanishing as layers are stacked.
- Robotics and vision. Robot and camera orientations are matrices in : rotations of .
- Recent optimizers. Muon orthogonalizes each weight matrix update using a Newton–Schulz iteration.
This lesson solves the inverse problem: given any matrix , construct an orthonormal basis of its column space while recording how the columns of are written in that basis. The result is factorization . You will build it three ways (classical Gram–Schmidt, modified Gram–Schmidt and Householder), measure which preserves orthogonality for ill-conditioned matrices, and use it to solve least squares without squaring the condition number, the danger noted last lesson.
Orthogonal matrices: transformations that do not distort
The name is unfortunate: a matrix whose columns are orthogonal but not unit vectors is not called orthogonal. has perpendicular columns and satisfies ; divided by it is orthogonal.
For a square matrix, says is a left inverse; in finite dimensions this makes it the inverse, so too and rows are orthonormal. Inverting an orthogonal matrix means transposing it, requiring no arithmetic operations.
The situation changes if with has orthonormal columns. It still satisfies , but , of size and rank , cannot be identity: it is the orthogonal projector onto . We call these matrices with orthonormal columns, reserving “orthogonal” for square ones.
You will prove the four forward claims in the next exercise. The converse is surprising: preserving lengths suffices to preserve everything. Its proof uses the polarization identity.
Proof
Suppose for every , and apply it to :
The squares cancel in pairs, giving for all . With and we obtain .
∎Step 1 of 4. How do you start with the dot product?
Orthogonal matrices form a group: if , then , and is orthogonal too. The determinant splits the group in two: those with , forming the subgroup of rotations, and those with , reversing orientation like a mirror.
The plane: rotations and reflections
In we can write the whole of . The first column of is a unit vector, so it is for some . The second is unit and perpendicular to the first: there are only two candidates, , rotated counterclockwise, and , rotated clockwise. This gives exactly two families:
with and .
The first is rotation by angle . is reflection across the line at angle to axis : it fixes vector and negates its perpendicular, as double-angle formulas confirm. Composing with the same trigonometric formulas,
two mirrors make a rotation through twice their angle, and a rotation followed by a reflection is another reflection.
What you saw has a useful topological interpretation. The determinant is continuous in its entries and on takes only values , so no continuous path of orthogonal matrices takes a rotation to a reflection: has two separate pieces. The animation must leave and flatten the plane along the way. A right hand cannot become a left hand by rotating within the plane.
More dimensions and their numerical importance
In rotations always have a fixed axis (Euler’s theorem, seen using eigenvalues in the next lesson); their systematic study using quaternions and exponential maps is in the robotics module. In any dimension, reflections are elementary pieces: the Cartan–Dieudonné theorem says every matrix in is a product of at most reflections. You will encounter it almost for free with Householder.
For computation, length preservation matters. If a vector arrives with error , multiplying by produces error of the same length: neither amplified nor reduced. The condition number, maximum relative error amplification studied in lesson 16, is , the minimum possible. Multiplying another matrix by does not change its conditioning: . Orthogonal transformations can therefore be chained without worsening what they receive.
A random orthogonal matrix
Orthogonal initialization and many experiments need “uniformly random” orthogonal matrices: according to Haar measure on , the unique distribution invariant under multiplication by a fixed orthogonal matrix. The standard recipe previews this lesson’s protagonist: take from QR factorization of a Gaussian matrix, which works because the standard Gaussian is rotation invariant. There is a trap: QR is unique only up to signs, and library convention biases the result. With LAPACK, as you will see, has sign opposite , so is always negative. Correct this by multiplying columns of by signs of the diagonal of (Mezzadri, 2007), as scipy.stats.ortho_group and torch.nn.init.orthogonal_ do.
import numpy as np
rng = np.random.default_rng(0)
def ortogonal_al_azar(n, rng, corregir=True):
Q, R = np.linalg.qr(rng.standard_normal((n, n)))
if corregir:
Q = Q * np.sign(np.diag(R)) # Q D, con D = diag(sgn r_kk): Haar
return Q
for corregir in (False, True):
q11 = np.array([ortogonal_al_azar(4, rng, corregir)[0, 0]
for _ in range(2000)])
print(f"corregir = {corregir!s:5} q11 > 0 en el "
f"{100 * np.mean(q11 > 0):5.1f} % media de q11: {q11.mean(): .3f}")
Q = ortogonal_al_azar(4, rng)
print("‖QᵀQ − I‖ =", np.linalg.norm(Q.T @ Q - np.eye(4)),
" det Q =", round(np.linalg.det(Q), 12))Gram–Schmidt: subtracting shadows
Let be linearly independent. We want orthonormal vectors spanning the same space, in the same order: the first of should span the same as the first of , for each . This extra requirement makes the result a useful factorization.
The idea uses orthogonal projection. If is unit, the shadow of on the line of is , and is perpendicular to . Gram–Schmidt repeats this: subtract each new vector’s shadow on everything already built, then normalize what remains.
Proof
Induct on . For , because it belongs to an independent family, and spans the same line.
Suppose the result holds through . If , then , contradicting independence; thus . For , using orthonormality of the previous ,
so is unit and perpendicular to the earlier vectors. Finally, is a combination of and , while : each span is contained in the other.
∎Nothing in the proof assumes vectors are columns of numbers: Gram–Schmidt works in any inner product space. Applied to monomials with , the shadow of on is and on is zero by symmetry, so the second remainder is ; the next is . Up to scale, these are Legendre polynomials. The same operation on monomial values at grid points is QR of a Vandermonde matrix: the lab shows monomials are a poor, nearly dependent basis, and QR turns them into an orthonormal basis of discrete orthogonal polynomials.
What matters in the observation:
- Remainders may be tiny. When is nearly in the previous vectors’ plane, is the difference of nearly equal vectors and its shadow. If of survives, relative data error becomes relative error around in . This is catastrophic cancellation, and no care in normalization fixes it.
- Error has a direction. What leaks into are remnants of components meant to be removed, i.e. along . The symptom is not with wrong length (it is normalized at the end), but no longer perpendicular to previous vectors.
- Double precision hides this unless vectors are extraordinarily close. Three-digit arithmetic, with unit roundoff instead of , magnifies the same phenomena to a visible scale.
QR factorization
Solving for from the definition of gives
which is column of a matrix product: column of is times a vector whose entries below are zero.
In the previous example,
Proof
Existence follows from the previous theorem. For uniqueness, let be any reduced QR with positive diagonal. Since is upper triangular with nonzero diagonal, are combinations of and vice versa (the inverse of an upper triangular matrix is also upper triangular), so for each . Then is a unit vector in perpendicular to , a subspace of dimension inside , which has dimension . Only two such vectors exist, opposite one another, and selects one. Once is fixed, is determined.
∎Without the sign condition, QR is unique up to a matrix : . Remember this when comparing your implementation with NumPy’s, which does not require positive diagonal.
Full QR also answers a question about the four subspaces: is an orthonormal basis of and , perpendicular to it, is an orthonormal basis of its complement .
The diagonal of also tells a story. If is square, , and since is the distance of from previous vectors, is the “base times height” formula for determinant as volume: the parallelogram area of is , and each new column multiplies by its height above the previous ones. In the example ; the negative sign comes from .
Gram–Schmidt performs : it right-multiplies by triangular matrices until orthonormal. Trefethen and Bau call this triangular orthogonalization. It costs about flops, the same order as Gaussian elimination; the problem, as you will see, is not cost.
Modified Gram–Schmidt: same arithmetic, different rounding
There are two ways to organize the same subtractions. Classical Gram–Schmidt (CGS) computes all shadows of from the original vector, , and subtracts them together. Modified Gram–Schmidt (MGS) subtracts each shadow immediately and projects the partially cleaned vector:
starting at and ending at .
In exact arithmetic these are the same algorithm: , because . Written with projectors, CGS applies at once, with , while MGS applies elementary projectors one after another:
Expanding the product produces cross terms with factors , zero if the are exactly orthonormal. In floating point they are not, and the difference matters: MGS projects the already corrected vector, so each step also removes components rounding leaked into previous ones, whereas CGS computes every shadow from the uncorrected vector and propagates orthogonality errors of previous .
In code the difference is one line:
# CGS: todas las sombras, calculadas sobre la columna original
r = Q[:, :k].T @ A[:, k]
v = A[:, k] - Q[:, :k] @ r
# MGS: cada sombra, calculada sobre el vector que se va limpiando
v = A[:, k].copy()
for j in range(k):
R[j, k] = Q[:, j] @ v
v = v - R[j, k] * Q[:, j]
How much is generally lost? The answer depends on condition number , the ratio of maximum and minimum stretch applied by to unit vectors, and unit roundoff (machine precision). Known results are:
- MGS: (Björck, 1967).
- CGS: , provided is small; otherwise there is no guarantee (Giraud, Langou, Rozložník and van den Eshof, 2005).
- Householder (next section): , independent of .
Where do these powers of come from? Rigorous analysis is delicate, but the CGS mechanism appears in one line. In exact arithmetic, : the Gram–Schmidt is a Cholesky factor of , and CGS, computing each column of from dot products of original columns, behaves as if factoring . Suppose computed satisfies with , and . Then
where the last equality uses : stretches exactly as . CGS pays the same price as normal equations for the same reason: implicitly it works with . MGS errors instead correspond to an orthogonal transformation applied to a slightly perturbed , introducing only one factor . Householder does not depend on at all.
Constants depend on and polynomially and modestly. Do not just believe the bounds: measure them.
Three observations from the experiment:
- Slopes match theory. Each decade of costs CGS two digits of orthogonality and MGS one. At , typical of moderate-degree polynomial regression, CGS no longer returns an orthonormal basis.
- MGS is not a complete remedy. With its columns have dot products between and (of order ): treating that as orthogonal (e.g. to compute ) inherits the error.
- Reorthogonalization works. A second CGS projection (CGS2) restores orthogonality to as long as is not numerically singular: “twice is enough”, proved by Giraud and coauthors in the cited article. It costs twice as much, but CGS2 uses matrix-vector products that parallelize well and require one synchronization per pass, whereas MGS chains dependent dot products. Large-scale Krylov methods (Arnoldi, GMRES) therefore often use CGS2.
Householder reflections: triangularizing with mirrors
Gram–Schmidt builds column by column and loses orthogonality along the way. The alternative reverses the approach: apply to a sequence of orthogonal transformations progressively making it triangular,
This is orthogonal triangularization. Each is orthogonal by construction, independent of previous calculations, and a product of orthogonal matrices is orthogonal, so is orthogonal regardless of . We need an orthogonal transformation that zeros all entries below a column’s diagonal. A suitably oriented mirror does this.
is symmetric, orthogonal and involutive (: reflecting twice returns each point). Check it.
Step 1 of 4. Why is it symmetric?
The key is that a mirror always maps one vector to another of the same length. If and , take . Then and
The mirror is the perpendicular-bisector hyperplane of the segment joining to . To zero all of except its first entry, two equal-length destinations are possible, , and choosing badly is a classic mistake.
The analysis takes one line. With destination , the first component of is . If makes a small angle with , then and : subtracting numbers agreeing in their first digits leaves relative error of order , and computed deviates from the axis by a fraction of order . Error grows until ; for smaller angles the wrong mirror barely moves and error falls again, as . Worst case, in double precision, loses half the digits. Choosing destination gives
a sum of two same-sign numbers that cannot cancel. Here choose : NumPy’s np.sign returns at , and then and the mirror maps to without zeroing anything. If the positive destination is required, formula , algebraically identical for , avoids subtraction.
Notice the subtlety: with the wrong sign remains perfectly orthogonal, because any defines a mirror. The problem is that it is no longer the desired mirror, and the entry meant to vanish does not. Error breaks triangularity, not orthogonality, and with it the accuracy of .
Householder QR
At step earlier columns already have zeros below the diagonal; for column consider only segment from the diagonal down. Build reflector of size mapping to a multiple of and apply it to rows of columns . The full transformation is block diagonal , leaving completed rows untouched. For an of :
The result is of full QR: triangle above a row of zeros.
Three details turn this into the production algorithm:
- is not formed. Store only the vectors , which fit in the lower triangle of as the algorithm zeros it. LAPACK normalizes and separately stores scalar with ; this is what
np.linalg.qr(A, mode="raw")returns. - Applying is cheap. Compute reflector by reflector, with a dot product and an update per step: about flops, never building an matrix or . Explicitly forming costs order extra flops and is needed only if its columns are required.
- Total cost of obtaining is about flops: like Gram–Schmidt if , and for a square matrix, twice LU factorization.
The decisive property: Householder QR is backward stable. Computed factors are the exact QR of a matrix with , and defined by computed reflectors is orthogonal to (Trefethen and Bau, lecture 16). This is the best result to expect of a floating-point algorithm; study backward stability in numerical methods.
A debugging tip: since each column’s destination is , Householder’s diagonal has opposite sign to the first entry of each processed column. Thus np.linalg.qr often returns negative diagonals. If you need the unique QR with positive diagonal, change signs of the corresponding columns of and rows of .
Givens rotations: zeroing one entry at a time
A Householder reflector zeros an entire column below the diagonal at once. Sometimes this is too much: when a matrix already has most needed zeros, use a surgical instrument.
To zero entry in row using entry in row of the same column, choose so vector rotates to the axis:
Calculate with np.hypot(a, b): the naive formula overflows if or exceeds , because their squares no longer fit in float64. is unnecessary: and suffice.
A dense matrix needs one rotation per entry below the diagonal, and Givens QR costs about flops, 50% more than Householder (Golub and Van Loan, section 5.2). Givens wins when structure leaves few entries to zero:
- Hessenberg matrices (zeros below the subdiagonal): rotations and flops instead of . This is the central step of the QR eigenvalue algorithm.
- Updating a factorization. If you have for least squares and a new observation arrives, adding row below gives a matrix triangularized with rotations in , without recomputing QR for all data. This underlies QR updates, recursive least squares and stable Kalman-filter variants; you will implement it in the exercises.
- Parallelism and sparsity. Rotations on disjoint row pairs are independent, and a rotation preserves zeros in columns where both rows already have zero.
Least squares with QR
Let have rank and be its reduced QR, completed to . Since preserves norms, minimizing can be rewritten in the basis of :
In practice compute by applying reflectors (or MGS on the augmented matrix, as you will see), and solve by back substitution. The same follows from normal equations: , so , and canceling invertible gives . Incidentally, is a Cholesky factor of .
If both paths reach the same , why not simply form ? Conditioning. If stretches unit vectors between and , then stretches them between and (immediate if is diagonal; the general case follows from SVD), so
Normal equations solve a system whose matrix has squared conditioning, and relative error behaves as . With , that is all digits gone. Householder QR works on and is backward stable, so error is governed by the problem’s own sensitivity. A nuance: under perturbations of , the least-squares condition number is of order , where is the angle between and its projection , and (Trefethen and Bau, lecture 18). If the model fits well (small ), sensitivity is of order and QR gains a factor ; with a large residual, term is unavoidable by any method.
What do everyday libraries do? np.linalg.lstsq and scipy.linalg.lstsq (default driver gelsd) use SVD, more expensive than QR but robust when is rank deficient; scipy.linalg.lstsq(A, b, lapack_driver="gelsy") uses column-pivoted QR, seen later. Scikit-learn’s LinearRegression calls scipy.linalg.lstsq, and statsmodels’ OLS defaults to the pseudoinverse and supports method="qr". None forms .
Implementation: three QR methods from scratch
The three factorizations fit on one screen. Notice Householder returns the reflectors rather than , and the two functions operating on them.
import numpy as np
def cgs(A):
"""Gram-Schmidt clásico: r_jk = q_j^T a_k, con la columna original."""
A = np.asarray(A, dtype=float)
m, n = A.shape
Q, R = np.zeros((m, n)), np.zeros((n, n))
for k in range(n):
R[:k, k] = Q[:, :k].T @ A[:, k] # todas las sombras de golpe
v = A[:, k] - Q[:, :k] @ R[:k, k]
R[k, k] = np.linalg.norm(v)
Q[:, k] = v / R[k, k]
return Q, R
def mgs(A):
"""Gram-Schmidt modificado: cada sombra se resta al calcularla."""
V = np.array(A, dtype=float) # copia: las pendientes se van limpiando
m, n = V.shape
Q, R = np.zeros((m, n)), np.zeros((n, n))
for k in range(n):
R[k, k] = np.linalg.norm(V[:, k])
Q[:, k] = V[:, k] / R[k, k]
R[k, k + 1:] = Q[:, k] @ V[:, k + 1:] # sombras sobre q_k
V[:, k + 1:] -= np.outer(Q[:, k], R[k, k + 1:])
return Q, R
def householder(A):
"""QR de Householder con Q implícita: reflectores v_k unitarios y R."""
R = np.array(A, dtype=float)
m, n = R.shape
V = []
for k in range(n):
x = R[k:, k]
v = x.copy()
v[0] += np.copysign(np.linalg.norm(x), x[0]) # signo estable
v /= np.linalg.norm(v)
R[k:, k:] -= 2.0 * np.outer(v, v @ R[k:, k:]) # solo filas k..m
V.append(v)
return V, np.triu(R[:n])
def apply_qt(V, b):
"""Q^T b sin formar Q: aplica H_1, ..., H_n en ese orden."""
b = np.array(b, dtype=float)
for k, v in enumerate(V):
b[k:] -= 2.0 * v * (v @ b[k:])
return b
def form_q(V, m):
"""Q reducida explícita (m x n): H_1 ... H_n aplicadas a I[:, :n]."""
Q = np.eye(m)[:, :len(V)]
for k in reversed(range(len(V))):
Q[k:, :] -= 2.0 * np.outer(V[k], V[k] @ Q[k:, :])
return Q
rng = np.random.default_rng(0)
A = rng.standard_normal((6, 4))
V, Rh = householder(A)
I4 = np.eye(4)
for nombre, (Q, R) in [("CGS", cgs(A)), ("MGS", mgs(A)),
("Householder", (form_q(V, 6), Rh))]:
print(f"{nombre:12s} ‖QR − A‖ = {np.linalg.norm(Q @ R - A):.1e}"
f" ‖QᵀQ − I‖ = {np.linalg.norm(Q.T @ Q - I4):.1e}")
print("diagonal de R (Householder):", np.diag(Rh).round(3))
print("primera columna de A: ", A[:, 0].round(3))For a well-conditioned random matrix the three are indistinguishable. Notice the sign of : opposite , as the stable choice predicts. np.copysign also handles the trap of , because np.copysign(1.0, 0.0) equals .
The example’s Läuchli matrix separates the three immediately:
eps = 1e-8 # eps² = 1e-16 < u: en coma flotante, 1 + eps² == 1
L = np.array([[1, 1, 1], [eps, 0, 0], [0, eps, 0], [0, 0, eps]])
print("¿1 + eps² == 1?", 1 + eps**2 == 1)
metodos = [("CGS", cgs(L)[0]), ("MGS", mgs(L)[0]),
("Householder", form_q(householder(L)[0], 4))]
for nombre, Q in metodos:
G = Q.T @ Q
print(f"{nombre:12s} q1·q2 = {G[0, 1]: .1e} q1·q3 = {G[0, 2]: .1e}"
f" q2·q3 = {G[1, 2]: .1e}")The CGS matches the hand calculation. MGS leaves at level, but is of order : its loss, with . Householder loses nothing.
Now repeat the interactive race with two classic ill-conditioned families: Hilbert matrices and Vandermonde matrices from polynomial fitting on .
import matplotlib.pyplot as plt
def hilbert(n):
i = np.arange(1, n + 1)
return 1.0 / (i[:, None] + i[None, :] - 1) # h_ij = 1/(i + j − 1)
def perdida(Q):
return np.linalg.norm(Q.T @ Q - np.eye(Q.shape[1]), 2)
def medir(A):
Qh = form_q(householder(A)[0], A.shape[0])
return (np.linalg.cond(A), perdida(cgs(A)[0]), perdida(mgs(A)[0]),
perdida(Qh))
hil = np.array([medir(hilbert(n)) for n in range(2, 13)])
t = np.linspace(0, 1, 50)
van = np.array([medir(np.vander(t, n, increasing=True))
for n in range(2, 19, 2)])
print(" n κ(H_n) CGS MGS Householder")
for n, (k, c, mg, h) in zip(range(2, 13), hil):
print(f"{n:2d} {k:9.1e} {c:9.1e} {mg:9.1e} {h:9.1e}")
u = np.finfo(float).eps / 2
kk = np.logspace(0, 17, 50)
fig, ax = plt.subplots(figsize=(7, 4.2))
for j, nombre in enumerate(["CGS", "MGS", "Householder"], start=1):
linea, = ax.loglog(hil[:, 0], hil[:, j], "o-",
label=f"{nombre} (Hilbert)")
ax.loglog(van[:, 0], van[:, j], "s--", color=linea.get_color(),
alpha=0.6, label=f"{nombre} (Vandermonde)")
for f, txt in [(u * kk**2, "uκ²"), (u * kk, "uκ"), (u + 0 * kk, "u")]:
ax.loglog(kk, f, ":", color="gray", lw=1)
ax.annotate(txt, (kk[-1], min(f[-1], 3)), fontsize=9, color="gray")
ax.set_ylim(1e-17, 10)
ax.set_xlabel("κ(A)")
ax.set_ylabel("‖QᵀQ − I‖₂")
ax.set_title("Pérdida de ortogonalidad frente al condicionamiento")
ax.legend(fontsize=8, ncol=2)
plt.show()Both families fall on the same lines: governs, not the matrix’s origin. Hilbert , with , already strips CGS of orthogonality.
Finally, the decisive experiment following Trefethen and Bau (lecture 19): fit on with a degree-14 polynomial by least squares using points. Vector is divided by , the exact solution’s last coefficient, so the correct answer is and error can be read directly.
from scipy.linalg import solve_triangular
m, n = 100, 15
t = np.linspace(0, 1, m)
A = np.vander(t, n, increasing=True) # columnas 1, t, ..., t^14
b = np.exp(np.sin(4 * t)) / 2006.787453080206 # así el x_15 exacto vale 1
print(f"κ(A) = {np.linalg.cond(A):.1e}")
V, R = householder(A)
x_house = solve_triangular(R, apply_qt(V, b)[:n])
Qm, Rm = mgs(A)
x_mgs = solve_triangular(Rm, Qm.T @ b) # Q^T b con una Q no ortogonal
Qa, Ra = mgs(np.column_stack([A, b])) # MGS sobre [A b]: Q^T b sale
x_mgs_amp = solve_triangular(Ra[:n, :n], Ra[:n, n]) # en la columna final
x_normal = np.linalg.solve(A.T @ A, A.T @ b) # ecuaciones normales
x_lstsq = np.linalg.lstsq(A, b, rcond=None)[0] # LAPACK (vía la SVD)
soluciones = {"Householder": x_house, "MGS con Qᵀb": x_mgs,
"MGS sobre [A b]": x_mgs_amp,
"ecuaciones normales": x_normal, "np.linalg.lstsq": x_lstsq}
for nombre, x in soluciones.items():
res = np.linalg.norm(A @ x - b)
print(f"{nombre:20s} x15 = {x[-1]: .10f} error = {abs(x[-1] - 1):.0e}"
f" ‖Ax − b‖ = {res:.3e}")With :
- Householder and
np.linalg.lstsqachieve 6–8 correct digits (exact figures depend on BLAS and operation order): errors below , the limit imposed by problem sensitivity. - Normal equations fail completely, even in sign: greatly exceeds . Their residual is only a few times optimal: a small residual does not guarantee an accurate solution in an ill-conditioned problem.
- MGS with loses several more digits than Householder because its is not orthogonal. But MGS on augmented matrix obtains with the same operations applied to columns, recovering Householder accuracy. This is no coincidence: MGS is numerically equivalent to Householder applied to the matrix formed by placing zero block above (Björck and Paige, 1992); the equivalence is lost if separately computed is used.
The professional version: NumPy and SciPy
np.linalg.qr calls LAPACK routine geqrf, blocked Householder: it groups reflectors into transformation for application via matrix products, which use cache much better. Its modes correspond to what you implemented:
import scipy.linalg as sla
A = rng.standard_normal((6, 3))
b = rng.standard_normal(6)
Q, R = np.linalg.qr(A) # reducida: Q 6x3, R 3x3
Qc, Rc = np.linalg.qr(A, mode="complete") # completa: Q 6x6, R 6x3
print("formas:", Q.shape, R.shape, "|", Qc.shape, Rc.shape)
Q2 = Qc[:, 3:] # las columnas que añade la completa
print("Q₂ es base de null(Aᵀ):", np.abs(A.T @ Q2).max() < 1e-12)
print("diagonal de R en NumPy:", np.diag(R).round(3))
V, Rh = householder(A)
print("misma R que nuestro Householder:", np.allclose(Rh, R))
d = np.sign(np.diag(R)) # diagonal positiva: la QR única
Qp, Rp = Q * d, d[:, None] * R
print("QR con diagonal positiva:", np.allclose(Qp @ Rp, A),
np.diag(Rp).round(3))
h, tau = np.linalg.qr(A, mode="raw") # formato LAPACK: reflectores y τ_k
print("raw:", h.shape, tau.round(3))
qtb, _ = sla.qr_multiply(A, b, mode="right") # b Q = (Qᵀb)ᵀ, sin formar Q
print("Qᵀb implícito == explícito:", np.allclose(qtb, Q.T @ b))Your Householder implementation and LAPACK give the same , signs included, because both choose the stable destination. Mode "raw" returns the reflector matrix transposed (for Fortran-order compatibility) and ; scipy.linalg.qr_multiply applies or without forming it.
QR has one final use shared with the more expensive SVD: revealing rank. If has nearly dependent columns, some is tiny, but without reordering it can appear anywhere. Column-pivoted QR, , selects at each step the remaining column with largest norm after subtracting previous shadows, producing with redundant columns at the end.
rng = np.random.default_rng(1)
N = 200
x1, x2, x3 = rng.standard_normal((3, N))
ruido = rng.standard_normal((2, N))
X = np.column_stack([
np.ones(N), x1, x2,
x1 + x2 + 1e-9 * ruido[0], # casi la suma de dos columnas
x3,
3 * x1 - 2 * x3 + 1e-11 * ruido[1], # casi combinación de otras dos
])
_, R0 = np.linalg.qr(X)
Qp, Rp, perm = sla.qr(X, mode="economic", pivoting=True)
s = np.linalg.svd(X, compute_uv=False)
np.set_printoptions(precision=2)
print("|diag R| sin pivoteo:", np.abs(np.diag(R0)))
print("|diag R| con pivoteo:", np.abs(np.diag(Rp)))
print("valores singulares: ", s)
print("orden de las columnas:", perm)
for tau in [np.finfo(float).eps * max(X.shape), 1e-6]:
r = int((np.abs(np.diag(Rp)) > tau * abs(Rp[0, 0])).sum())
sobran = sorted(perm[r:].tolist())
print(f"tolerancia relativa {tau:.0e}: rango {r}, sobran {sobran}")Three lessons from one output:
- Without pivoting, small occur in positions 4 and 6, the columns constructed from earlier ones. Pivoting moves them to the end, and the diagonal decreases much like the singular values it closely tracks.
- Numerical rank depends on tolerance. At machine tolerance all six columns are independent: the two smallest , around and , are well above threshold . With tolerance appropriate to data precision, e.g. for six-digit measurements, two are redundant. This is numerical rank, formalized with SVD.
- Pivoting says how many columns are redundant and chooses which, not “the culprits”. Here it discards and , just as redundant as the constructed columns: dependence belongs to the set. Selection favors larger-norm columns; standardizing variables first changes the result.
For rank deficiency (which of infinitely many solutions to choose) and tolerance selection, see pivoted QR in numerical methods and the pseudoinverse in lesson 18. To add or remove rows or columns from an existing QR, scipy.linalg.qr_insert, qr_delete and qr_update use Givens rotations without refactorization.
Common mistakes
Exercises
More than one answer may be correct.
householder_qr(A) without np.linalg.qr or scipy.linalg.qr. Return Q (, orthonormal columns) and R (, upper triangular with positive diagonal) satisfying , for full-rank with . Tests check reconstruction, shape of R, a column starting with 0, and for ill-conditioned Hilbert and Vandermonde matrices, which Gram–Schmidt does not pass.import numpy as np
def householder_qr(A):
"""Devuelve Q (m x n) y R (n x n, triangular superior, diagonal positiva) con A = QR."""
A = np.array(A, dtype=float)
m, n = A.shape
# tu código aquí
raise NotImplementedErrorqr_add_row(R, c, a, beta): given (, upper triangular) and of the current problem, add observation using Givens rotations between each row of and the new row , and return (R_nueva, c_nueva, gamma), where gamma is the new row's last entry after rotations, satisfying . Use np.hypot and do not modify arguments.import numpy as np
def qr_add_row(R, c, a, beta):
"""Añade la observación (a, beta) a un problema de mínimos cuadrados ya factorizado.
R: n x n triangular superior; c = Q^T b (longitud n).
Devuelve (R_nueva, c_nueva, gamma), con ‖r_nuevo‖² = ‖r‖² + gamma²."""
# tu código aquí: n rotaciones de Givens entre la fila j de [R c] y la fila nueva [a beta]
raise NotImplementedErrorSummary
- A matrix is orthogonal if square and . It preserves dot products, lengths and angles; separates rotations from reflections, two pieces no continuous path joins. If rectangular with orthonormal columns, is a projector.
- Gram–Schmidt subtracts each vector’s shadow on previous vectors and normalizes. Its record is QR, , unique with positive diagonal, where is the distance from to previous vectors.
- In floating point, cancellation subtracting shadows destroys orthogonality: CGS loses as , MGS as , and Householder stays at . Reorthogonalization (CGS2) also works.
- Householder reflectors triangularize with mirrors orthogonal by construction; stable sign avoids cancellation, and is stored and applied implicitly. Givens rotations zero individual entries: ideal for structured matrices and factorization updates.
- For least squares, avoids forming , whose conditioning is .