Module contents
Lesson 5 of 26Core 100 min

Orthogonalization and least squares: Householder, Givens and QR

Orthogonal transformations avoid amplifying errors. Study orthogonalization with Householder reflections and Givens rotations, losses of orthogonality in Gram–Schmidt, implicit Householder QR, updating factorizations with Givens, and rank-deficient least squares with pivoted QR and truncated SVD.

After this lesson you can

  • Implement Householder QR by saving reflectors without forming Q.
  • Measure and explain loss of orthogonality in classical, modified and reorthogonalized Gram–Schmidt.
  • Solve least squares by QR and SVD, and explain why normal equations square κ.
  • Update a QR factorization when adding rows using Givens rotations.
  • Determine numerical rank and the minimum-norm solution of a rank-deficient problem.

Before you start

Motivation: a regression gone wrong

You have 40 measurements of a noisy periodic signal and want to fit a polynomial of moderate degree pp, between 4 and 12. The independent variable is a date or temperature in [1,2][1, 2], so you write the model in powers 1,t,t2,…,tp1, t, t^2, \dots, t^p and solve the least-squares problem min⁡c∥Xc−y∥2\min_{\vb{c}}\norm{\mat{X}\vb{c} - \vb{y}}_2 in the most direct way you know, with the normal equations X⊤Xc=X⊤y\mat{X}\T\mat{X}\vb{c} = \mat{X}\T\vb{y}.

[ ]A regression gone wrongBrowser
import numpy as np

rng = np.random.default_rng(1)
s = np.linspace(0, 1, 40)
y = np.sin(2 * np.pi * s) + 0.1 * rng.standard_normal(40)
t = 1 + s                                    # las mismas medidas, con la variable en [1, 2]
tt = np.linspace(1, 2, 400)

print("grado  kappa(X)  kappa(X)^2  Cholesky  dif. coeficientes  residuo NE / lstsq  distancia curvas")
for p in range(4, 13):
    X = np.vander(t, p + 1, increasing=True)    # columnas 1, t, ..., t^p
    G, h = X.T @ X, X.T @ y
    try:                                        # según la plataforma, Cholesky lanza un error o devuelve NaN
        chol = "funciona" if np.all(np.isfinite(np.linalg.cholesky(G))) else "falla"
    except np.linalg.LinAlgError:
        chol = "falla"
    c_ne = np.linalg.solve(G, h)                # ecuaciones normales por eliminación gaussiana
    c_ls = np.linalg.lstsq(X, y, rcond=None)[0] # LAPACK: SVD
    k = np.linalg.cond(X)
    dif = np.linalg.norm(c_ne - c_ls) / np.linalg.norm(c_ls)
    exceso = np.linalg.norm(X @ c_ne - y) / np.linalg.norm(X @ c_ls - y)
    dist = np.max(np.abs(np.vander(tt, p + 1, increasing=True) @ (c_ne - c_ls)))
    print(f"{p:4d}   {k:9.1e}  {k * k:9.1e}   {chol:8s}  {dif:12.1e}        {exceso:12.4f}       {dist:9.1e}")
print(f"\n1/u = {2.0**53:.1e}")

Read the table from top to bottom. Through degree 6 the solutions agree to at least three digits. At degree 7 coefficients differ by 3 %, and from degree 8 they have no digits in common: relative differences are 91 % and then 100 %. At degree 9 two other symptoms appear. Cholesky, which should work for any full-rank X⊤X\mat{X}\T\mat{X}, fails. And the normal-equations residual is 29 % greater than that of lstsq: this is not another equally good answer to an ill-conditioned problem; the problem has not been solved, because a coefficient vector fits the same data better. The curves, however, differ by at most 0.130.13, and much less at other degrees: normal-equation errors lie in directions that barely change the curve over the data, so the failure goes unnoticed if you only look at the graph. (A practical detail: depending on the platform, np.linalg.cholesky raises an error or silently returns a matrix with NaN; the cell checks both.)

The κ\kappa columns diagnose the problem. At degree 8, κ2(X)≈3×109\kappa_2(\mat{X}) \approx 3\times 10^{9} is high but manageable in double precision: a stable algorithm can give about 6 coefficient digits. But normal equations work with X⊤X\mat{X}\T\mat{X}, whose condition number is κ2(X)2≈1019\kappa_2(\mat{X})^2 \approx 10^{19}, a thousand times greater than 1/u≈9×10151/u \approx 9\times 10^{15}. By linear-system perturbation theory, rounding just when forming X⊤X\mat{X}\T\mat{X} is enough to make the matrix indistinguishable from a singular one; Cholesky completing at degree 8 and failing at degree 9 depends on rounding luck. The threshold is where the table says: coefficients deteriorate as κ2\kappa^2 approaches 1/u1/u (degree 7) and are lost completely when it exceeds it. In the conditioning lesson you saw the same with t∈[0,1]t \in [0, 1] and degree 12; here degree 8 suffices because the powers of t∈[1,2]t \in [1, 2] are even more alike.

This lesson gives the full numerical answer. Orthogonal matrices do not amplify errors, making them the tools for stable least-squares, eigenvalue and SVD algorithms. From the linear algebra orthogonality lesson you already know Gram–Schmidt, Householder reflectors and Givens rotations. Here we study their floating-point behavior and actual implementation: why classical Gram–Schmidt loses orthogonality in proportion to κ2\kappa^2 and modified Gram–Schmidt to κ\kappa, how LAPACK stores reflectors without forming Q\mat{Q}, how to update a factorization when new data arrive, why normal equations square κ\kappa, and what to do with a rank-deficient matrix.

Why orthogonal transformations are stable

An Q\mat{Q} matrix with Q⊤Q=I\mat{Q}\T\mat{Q} = \mat{I} preserves the Euclidean norm: ∥Qx∥22=x⊤Q⊤Qx=∥x∥22\norm{\mat{Q}\vb{x}}_2^2 = \vb{x}\T\mat{Q}\T\mat{Q}\vb{x} = \norm{\vb{x}}_2^2. Consequently ∥Q∥2=∥Q⊤∥2=1\norm{\mat{Q}}_2 = \norm{\mat{Q}\T}_2 = 1 and κ2(Q)=1\kappa_2(\mat{Q}) = 1: an input error δx\delta\vb{x} emerges with exactly the same norm. Applied to a chain of transformations, this property makes orthogonal algorithms stable.

Compare Gaussian elimination. Each step multiplies by a Gauss transformation Lk=I−ℓkek⊤\mat{L}_k = \mat{I} - \boldsymbol{\ell}_k\vb{e}_k\T, which is not orthogonal: ∥Lk∥\norm{\mat{L}_k} can be large, and errors in one step are amplified in later steps. That is why Gaussian elimination analysis needs the growth factor, which can reach 2n−12^{n-1} with partial pivoting. Orthogonal transformations have no such growth.

Proof

By induction on kk. For k=1k = 1, P1=Q1(I+Q1⊤E1)\mat{P}_1 = \mat{Q}_1(\mat{I} + \mat{Q}_1\T\mat{E}_1) and ∥Q1⊤E1∥2=∥E1∥2≤ε\norm{\mat{Q}_1\T\mat{E}_1}_2 = \norm{\mat{E}_1}_2 \le \eps. Assume the result for k−1k - 1 and define W=Qk−1⋯Q1\mat{W} = \mat{Q}_{k-1}\cdots\mat{Q}_1, which is orthogonal. Then

PkPk−1⋯P1=(Qk+Ek)W(I+Fk−1)=QkW(I+W⊤Qk⊤EkW)(I+Fk−1).\mat{P}_k\mat{P}_{k-1}\cdots\mat{P}_1 = (\mat{Q}_k + \mat{E}_k)\mat{W}(\mat{I} + \mat{F}_{k-1}) = \mat{Q}_k\mat{W}\big(\mat{I} + \mat{W}\T\mat{Q}_k\T\mat{E}_k\mat{W}\big)(\mat{I} + \mat{F}_{k-1}).

The middle factor has ∥W⊤Qk⊤EkW∥2=∥Ek∥2≤ε\norm{\mat{W}\T\mat{Q}_k\T\mat{E}_k\mat{W}}_2 = \norm{\mat{E}_k}_2 \le \eps, because multiplication by orthogonal matrices preserves the 2-norm. Thus I+Fk=(I+G)(I+Fk−1)\mat{I} + \mat{F}_k = (\mat{I} + \mat{G})(\mat{I} + \mat{F}_{k-1}) with ∥G∥2≤ε\norm{\mat{G}}_2 \le \eps, and ∥Fk∥2≤∥G∥+∥Fk−1∥+∥G∥∥Fk−1∥≤(1+ε)(1+ε)k−1−1\norm{\mat{F}_k}_2 \le \norm{\mat{G}} + \norm{\mat{F}_{k-1}} + \norm{\mat{G}}\norm{\mat{F}_{k-1}} \le (1 + \eps)(1 + \eps)^{k-1} - 1.

∎

The key step is ∥W⊤Qk⊤EkW∥=∥Ek∥\norm{\mat{W}\T\mat{Q}_k\T\mat{E}_k\mat{W}} = \norm{\mat{E}_k}: the error at step kk can be moved back to the start of the chain without growing. If the Qj\mat{Q}_j were arbitrary matrices, this would multiply ∥Ek∥\norm{\mat{E}_k} by κ(W)\kappa(\mat{W}), and with kk ill-conditioned factors the bound would be exponential. Applying a Householder reflector in floating point is equivalent, column by column, to multiplying by an Pj\mat{P}_j of this kind with ε\eps of order mumu (Higham, chapter 19), yielding the lesson’s central result.

This is the theorem in chapter 19 of Higham (2002), and the normwise version of Trefethen and Bau (lecture 16). Three observations: the bound is columnwise: each column of A\mat{A} is perturbed little relative to its own norm, even if columns have very different scales. The theorem’s Q\mat{Q} is exactly orthogonal, and the computed one is orthogonal to uu, independently of κ(A)\kappa(\mat{A}): Gram–Schmidt does not achieve this. Nor does it say R^\hat{\mat{R}} is close to the exact R\mat{R}: if A\mat{A} is ill-conditioned, R^\hat{\mat{R}} may differ greatly entrywise and still be the exact R\mat{R} of a nearby matrix. This is pure backward stability; final accuracy depends on conditioning of the problem solved with it.

Gram–Schmidt in floating point

In Gram–Schmidt orthogonalization, column kk is orthogonalized against earlier columns by subtracting its projections. There are three ways to organize these subtractions, identical in exact arithmetic:

  • Classical (CGS): rjk=qj⊤akr_{jk} = \vb{q}_j\T\vb{a}_k for every j<kj < k with the original vector, and vk=ak−∑j<krjkqj\vb{v}_k = \vb{a}_k - \sum_{j<k} r_{jk}\vb{q}_j. In matrix form, vk=(I−Qk−1Qk−1⊤)ak\vb{v}_k = (\mat{I} - \mat{Q}_{k-1}\mat{Q}_{k-1}\T)\vb{a}_k: two matrix-vector products, which parallelize well.
  • Modified (MGS): rjk=qj⊤vk(j)r_{jk} = \vb{q}_j\T\vb{v}_k^{(j)} with the already partially cleaned vector, and vk(j+1)=vk(j)−rjkqj\vb{v}_k^{(j+1)} = \vb{v}_k^{(j)} - r_{jk}\vb{q}_j. This successively applies projectors (I−qk−1qk−1⊤)⋯(I−q1q1⊤)(\mat{I} - \vb{q}_{k-1}\vb{q}_{k-1}\T)\cdots(\mat{I} - \vb{q}_1\vb{q}_1\T).
  • With reorthogonalization (CGS2): repeat the classical step twice, w=(I−Qk−1Qk−1⊤)ak\vb{w} = (\mat{I} - \mat{Q}_{k-1}\mat{Q}_{k-1}\T)\vb{a}_k and vk=(I−Qk−1Qk−1⊤)w\vb{v}_k = (\mat{I} - \mat{Q}_{k-1}\mat{Q}_{k-1}\T)\vb{w}, adding both coefficient sets in R\mat{R}.

CGS and MGS cost about 2mn22mn^2 flops; CGS2 costs twice as much. All three give factorizations Q^R^\hat{\mat{Q}}\hat{\mat{R}} that reconstruct A\mat{A} to uu. They differ in orthogonality of Q^\hat{\mat{Q}}: this is the stability of classical and modified Gram–Schmidt, a quantitative result with precise assumptions.

The assumptions matter: CGS requires uκ2≪1u\kappa^2 \ll 1, meaning A⊤A\mat{A}\T\mat{A} must be numerically nonsingular; MGS and CGS2 require only uκ≪1u\kappa \ll 1, that A\mat{A} have numerical full rank. Outside these assumptions there is no guarantee: in the lab CGS with κ=1010\kappa = 10^{10} produces vectors that are not orthogonal even to one digit. The previous theorem’s Householder bounds assume nothing about κ\kappa. The 2005 paper is in Numerische Mathematik 101.

InteractiveLoss of orthogonality versus κ
For each κ\kappa, construct A=Udiag⁡(σ)V⊤\mat{A} = \mat{U}\diag(\sigma)\mat{V}\T of size 60×1560\times 15 with singular values in geometric progression from 1 to 1/κ1/\kappa, and factor it using all four algorithms in double precision in your browser. On log-log axes, CGS follows guide uκ2u\kappa^2 (slope 2) until saturation, MGS follows uκu\kappa (slope 1), and CGS2 and Householder stay at the uu floor. Switch to Reconstruction: all four reconstruct A\mat{A} to uu. Under Least squares, with exactly b=Ax\vb{b} = \mat{A}\vb{x}, compare MGS using Q^⊤b\hat{\mat{Q}}\T\vb{b} with MGS applied to the augmented matrix [A b][\mat{A}\ \vb{b}].

Where does the κ2\kappa^2 of CGS come from? The key to Giraud and coauthors’ proof is that the CGS R^\hat{\mat{R}} is a backward-stable Cholesky factor of A⊤A\mat{A}\T\mat{A}: R^⊤R^=A⊤A+E\hat{\mat{R}}\T\hat{\mat{R}} = \mat{A}\T\mat{A} + \mat{E} with ∥E∥≤c u∥A∥2\norm{\mat{E}} \le c\,u\norm{\mat{A}}^2. If also A+ΔA=Q^R^\mat{A} + \Delta\mat{A} = \hat{\mat{Q}}\hat{\mat{R}} with small ΔA\Delta\mat{A} (reconstruction is good), then

Q^⊤Q^=R^−T(A+ΔA)⊤(A+ΔA)R^−1=I−R^−T(E−A⊤ΔA−ΔA⊤A−ΔA⊤ΔA)R^−1,\hat{\mat{Q}}\T\hat{\mat{Q}} = \hat{\mat{R}}^{-\mathsf{T}}(\mat{A} + \Delta\mat{A})\T(\mat{A} + \Delta\mat{A})\hat{\mat{R}}^{-1} = \mat{I} - \hat{\mat{R}}^{-\mathsf{T}}\big(\mat{E} - \mat{A}\T\Delta\mat{A} - \Delta\mat{A}\T\mat{A} - \Delta\mat{A}\T\Delta\mat{A}\big)\hat{\mat{R}}^{-1},

and since ∥R^−1∥2≈1/σmin⁡(A)\norm{\hat{\mat{R}}^{-1}}_2 \approx 1/\sigma_{\min}(\mat{A}), the parenthesized term, of size u∥A∥2u\norm{\mat{A}}^2, is divided by σmin⁡2\sigma_{\min}^2: ∥I−Q^⊤Q^∥≲c uκ2\norm{\mat{I} - \hat{\mat{Q}}\T\hat{\mat{Q}}} \lesssim c\,u\kappa^2. In other words, inside, CGS is a Cholesky factorization of the normal equations, and inherits their κ2\kappa^2. This is not an analogy: the argument is the same as for the failure of normal equations in the motivation.

MGS avoids that mechanism because each projection is computed on the corrected vector, which has lost components introduced by rounding in earlier steps. The clearest analysis is by Björck and Paige (1992, Loss and recapture of orthogonality in the modified Gram-Schmidt algorithm, SIAM J. Matrix Anal. Appl.): MGS applied to A\mat{A} is numerically equivalent to Householder QR applied to the augmented matrix [OnA]\begin{bmatrix} \mat{O}_n \\ \mat{A} \end{bmatrix}, with nn rows of zeros above. Two everyday consequences follow:

  • MGS’s R^\hat{\mat{R}} is as good as Householder’s, although its Q^\hat{\mat{Q}} loses orthogonality in proportion to uκu\kappa.
  • For least squares, do not compute Q^⊤b\hat{\mat{Q}}\T\vb{b}. Apply MGS to [A b][\mat{A}\ \vb{b}] and take the last column of R^\hat{\mat{R}} as Q⊤b\mat{Q}\T\vb{b}: the same dot products, but with the progressively cleaned vector. This is backward stable; with Q^⊤b\hat{\mat{Q}}\T\vb{b} it is not. The interactive shows this in Least squares mode.

CGS2 is the practical remedy when vectors must be orthogonalized one by one and orthogonality is wanted to uu: the second pass cleans up what the first left, and a third adds nothing (“twice is enough,” an observation Parlett attributes to Kahan). It costs twice as much as CGS, but its matrix-vector products distribute well across threads and nodes, whereas MGS is inherently sequential within each column. Hence its common use in Arnoldi’s process for Krylov methods.

Householder in practice

Householder QR in practice involves three implementation decisions (the destination sign, compact reflector storage and implicit application of Q⊤\mat{Q}\T) that turn the Householder reflection into LAPACK routine geqrf.

A closer look at the sign

To zero all of x∈Rm\vb{x} \in \R^m except its first entry there are two destinations of equal length, ±∥x∥e1\pm\norm{\vb{x}}\vb{e}_1, and the reflector uses v=x−(destino)\vb{v} = \vb{x} - (\text{destino}). The remaining entries of v\vb{v} are those of x\vb{x}, copied without error; all arithmetic is in v1v_1. With destination +∥x∥e1+\norm{\vb{x}}\vb{e}_1 and x1>0x_1 > 0, v1=x1−∥x∥v_1 = x_1 - \norm{\vb{x}} subtracts nearly equal numbers when x\vb{x} is nearly aligned with e1\vb{e}_1. The interactive simulates 11- or 24-bit mantissa arithmetic (float16 and float32), rounding each operation so the phenomenon is visible at larger angles; float64 behaves the same with u=2−53u = 2^{-53}.

InteractiveThe Householder mirror
Left: x\vb{x}, the two possible destinations, the vector v\vb{v} joining the chosen destination to x\vb{x}, and the mirror perpendicular to v\vb{v}. Right: a magnified view near +∥x∥e1+\norm{\vb{x}}\vb{e}_1 with different scales on each axis; vertical lines represent numbers representable with pp bits. With the naive formula and small θ\theta, v1≈−∥x∥θ2/2v_1 \approx -\norm{\vb{x}}\theta^2/2 spans a few grid spacings, and the error in computed ∥x∥\norm{\vb{x}} (up to half a spacing) is comparable to all of v1v_1: the dashed v^\hat{\vb{v}} points elsewhere. Below, the entry that should vanish, ∣(H^x)2∣/∥x∥\abs{(\hat{\mat{H}}\vb{x})_2}/\norm{\vb{x}}, for all angles (mean of 12 radii): the naive formula follows guide u/θu/\theta down to θ≈u\theta \approx \sqrt{u} and guide θ\theta below; the stable and Parlett formulas stay at uu or below.

The magnified view shows a detail standard analysis misses. The subtraction x1−σ^x_1 - \hat\sigma, with σ^\hat\sigma the computed value of ∥x∥\norm{\vb{x}}, is exact in floating point when σ^/2≤x1≤2σ^\hat\sigma/2 \le x_1 \le 2\hat\sigma (Sterbenz’s lemma from catastrophic cancellation). Subtraction adds no error: it reveals the error already present in σ^\hat\sigma. That absolute error, about u∥x∥u\norm{\vb{x}}, is small relative to ∥x∥\norm{\vb{x}} but enormous relative to v1≈−∥x∥θ2/2v_1 \approx -\norm{\vb{x}}\theta^2/2: relative error in v^1\hat v_1 is of order 2u/θ22u/\theta^2, and normwise error in v^\hat{\vb{v}} is u/θu/\theta, because ∥v∥≈∥x∥θ\norm{\vb{v}} \approx \norm{\vb{x}}\theta. You will prove this in the guided exercise at the end. The entry that should vanish is then about u∥x∥/θu\norm{\vb{x}}/\theta.

The lower graph shows what happens for still smaller angles. When ∥x∥θ2/2\norm{\vb{x}}\theta^2/2 drops below half a grid spacing, that is, when θ≲u\theta \lesssim \sqrt{u}, the computed value is v^1=0\hat v_1 = 0: the computed mirror is the e1\vb{e}_1 axis itself, sending (x1,x2)(x_1, x_2) to (x1,−x2)(x_1, -x_2) and zeroing nothing, and the remaining entry is ∣x2∣≈∥x∥θ\abs{x_2} \approx \norm{\vb{x}}\theta. The branches u/θu/\theta and θ\theta cross at θ≈u\theta \approx \sqrt{u}, where error reaches its maximum, about u ∥x∥\sqrt{u}\,\norm{\vb{x}}. In float64 this is 10−810^{-8}: Householder QR with the naive sign loses half its digits in the worst case. The interactive starts there: with p=11p = 11 (u=2−11≈4.9×10−4u = 2^{-11} \approx 4.9\times 10^{-4}, u≈0.022\sqrt{u} \approx 0.022) and θ≈1.44°=0.025\theta \approx 1.44° = 0.025 rad, the exact v1v_1, −5.05×10−4-5.05\times 10^{-4}, spans half a grid spacing; the computed one, −9.77×10−4-9.77\times 10^{-4}, spans a full spacing, with 93 % relative error, and the entry that should vanish is 0.023 ∥x∥0.023\,\norm{\vb{x}}, 48 times uu.

There are two remedies, both in the interactive:

  • Choose destination −sign⁡(x1)∥x∥e1-\operatorname{sign}(x_1)\norm{\vb{x}}\vb{e}_1 so v1=x1+sign⁡(x1)∥x∥v_1 = x_1 + \operatorname{sign}(x_1)\norm{\vb{x}} is a sum of two numbers with the same sign. LAPACK does this with sign⁡(0)=+1\operatorname{sign}(0) = +1.
  • Keep the positive destination and rewrite the subtraction: v1=x1−∥x∥=−(x22+⋯+xm2)/(x1+∥x∥)v_1 = x_1 - \norm{\vb{x}} = -(x_2^2 + \cdots + x_m^2)/(x_1 + \norm{\vb{x}}) if x1>0x_1 > 0. This is Parlett’s formula (Golub and Van Loan, section 5.1.3), useful when a positive diagonal of R\mat{R} is desired.

How LAPACK stores reflectors

LAPACK routine dlarfg normalizes the reflector so its first entry is 1. Given x=(α,x2)\vb{x} = (\alpha, \vb{x}_2), it computes

β=−sign⁡(α)α2+∥x2∥2,τ=β−αβ,v=[1x2/(α−β)],\beta = -\operatorname{sign}(\alpha)\sqrt{\alpha^2 + \norm{\vb{x}_2}^2}, \qquad \tau = \frac{\beta - \alpha}{\beta}, \qquad \vb{v} = \begin{bmatrix} 1 \\ \vb{x}_2/(\alpha - \beta) \end{bmatrix},

and H=I−τvv⊤\mat{H} = \mat{I} - \tau\vb{v}\vb{v}\T then satisfies Hx=βe1\mat{H}\vb{x} = \beta\vb{e}_1. Denominator α−β\alpha - \beta is a sum of two numbers with the same sign, so it does not cancel either. Since α/β∈[−1,0]\alpha/\beta \in [-1, 0], scalar τ=1−α/β\tau = 1 - \alpha/\beta is always in [1,2][1, 2] (it equals 2/v⊤v2/\vb{v}\T\vb{v}, as required for H\mat{H} to be orthogonal). If x2=0\vb{x}_2 = \vb{0} there is nothing to zero and dlarfg returns τ=0\tau = 0, that is, H=I\mat{H} = \mat{I}.

The advantage of v1=1v_1 = 1 is that it need not be stored. In step kk, entries k+1,…,mk+1, \dots, m of column kk are zeroed, leaving exactly enough space for entries 2,…,m−k+12, \dots, m - k + 1 of vk\vb{v}_k. The matrix is overwritten as follows, for m=5m = 5 and n=3n = 3:

[r11r12r13v2(1)r22r23v3(1)v2(2)r33v4(1)v3(2)v2(3)v5(1)v4(2)v3(3)],τ=(τ1,τ2,τ3).\begin{bmatrix} r_{11} & r_{12} & r_{13} \\ v^{(1)}_2 & r_{22} & r_{23} \\ v^{(1)}_3 & v^{(2)}_2 & r_{33} \\ v^{(1)}_4 & v^{(2)}_3 & v^{(3)}_2 \\ v^{(1)}_5 & v^{(2)}_4 & v^{(3)}_3 \end{bmatrix}, \qquad \boldsymbol{\tau} = (\tau_1, \tau_2, \tau_3).

R\mat{R} occupies the upper triangle and reflectors the lower: no additional memory except the nn scalars τk\tau_k. This is exactly what np.linalg.qr(A, mode="raw") returns (transposed, since LAPACK stores by columns), and your lab implementation will reproduce it.

Apply Q⊤\mat{Q}\T without forming Q\mat{Q}

With Q=H1H2⋯Hn\mat{Q} = \mat{H}_1\mat{H}_2\cdots\mat{H}_n, product Q⊤b=Hn⋯H1b\mat{Q}\T\vb{b} = \mat{H}_n\cdots\mat{H}_1\vb{b} is computed reflector by reflector. Each Hk\mat{H}_k touches only entries k,…,mk, \dots, m and costs one dot product and one update:

bk:m←bk:m−τk vk (vk⊤bk:m),\vb{b}_{k:m} \leftarrow \vb{b}_{k:m} - \tau_k\,\vb{v}_k\,(\vb{v}_k\T\vb{b}_{k:m}),

with 4(m−k+1)4(m - k + 1) flops. In total, ∑k4(m−k+1)≈4mn−2n2\sum_k 4(m - k + 1) \approx 4mn - 2n^2 flops and no m×mm\times m matrix in memory. Forming the thin Q\mat{Q} (m×nm\times n) by backward accumulation, Q1=H1(H2(⋯(Hn[In;0])))\mat{Q}_1 = \mat{H}_1(\mat{H}_2(\cdots(\mat{H}_n[\mat{I}_n; \mat{0}]))), costs as much as factorization itself, and forming full Q\mat{Q} m×mm\times m costs still more and stores m2m^2 numbers: with m=106m = 10^6 observations, 8 TB. Least squares needs only Q⊤b\mat{Q}\T\vb{b}.

Cost

paso k: x=Ak:m, k∈Rm−k+1,bloque restante B=Ak:m, k+1:n∈R(m−k+1)×(n−k)\text{paso } k:\ \vb{x} = \mat{A}_{k:m,\,k} \in \R^{m-k+1},\quad \text{bloque restante } \mat{B} = \mat{A}_{k:m,\,k+1:n} \in \R^{(m-k+1)\times(n-k)}
Step k constructs the reflector for column k and applies it to the rest of the active submatrix.
1/4

If m≫nm \gg n, 2mn22mn^2, the same as Gram–Schmidt; if m=nm = n, 43n3\tfrac{4}{3}n^3, twice LU. This is the flop count needed to compare with normal equations.

Updating QR with Givens rotations

A Givens rotation zeros one entry by mixing two rows. For a dense matrix it costs more than Householder, but when the matrix is already almost triangular, zeroing the few remaining entries with rotations costs O(n2)\bigO(n^2) instead of O(mn2)\bigO(mn^2) for refactorization. This is updating QR factorizations.

Computing the rotation

To zero bb against aa, find c,sc, s with c2+s2=1c^2 + s^2 = 1 and

[cs−sc][ab]=[r0],r=a2+b2,c=a/r,s=b/r.\begin{bmatrix} c & s \\ -s & c \end{bmatrix}\begin{bmatrix} a \\ b \end{bmatrix} = \begin{bmatrix} r \\ 0 \end{bmatrix}, \qquad r = \sqrt{a^2 + b^2}, \quad c = a/r, \quad s = b/r.

Two numerical details. rr is computed with hypot, which scales before squaring: a2a^2 overflows in float64 if ∣a∣>10154\abs{a} > 10^{154} even when rr easily fits. No angle or trigonometric function is needed: cc and ss come from division. LAPACK routine dlartg does exactly this, taking extra care with a=0a = 0 or b=0b = 0. Applying the rotation to two rows of length LL costs 6L6L flops (four products and two sums per column).

Adding an observation

Suppose you have the QR of a least-squares problem with mm data points and observation m+1m + 1 arrives, a row a⊤\vb{a}\T with response β\beta. The trick is to factor the augmented matrix [A b][\mat{A}\ \vb{b}]: its triangular factor is

R~=[Rz0⊤ρ],z=Q1⊤b,ρ=∥Ax⋆−b∥2,\tilde{\mat{R}} = \begin{bmatrix} \mat{R} & \vb{z} \\ \vb{0}\T & \rho \end{bmatrix}, \qquad \vb{z} = \mat{Q}_1\T\vb{b}, \qquad \rho = \norm{\mat{A}\vb{x}^\star - \vb{b}}_2,

because the first nn columns give the QR of A\mat{A}, the projected last column is Q1⊤b\mat{Q}_1\T\vb{b}, and what remains of b\vb{b} outside col⁡(A)\col(\mat{A}) has norm ρ\rho, the residual of solution x⋆=R−1z\vb{x}^\star = \mat{R}^{-1}\vb{z}. All problem information, whatever mm, fits in an (n+1)×(n+1)(n+1)\times(n+1) matrix.

Proof

Write the matrix with the new observation as [Q00⊤1][R~0w⊤]\begin{bmatrix} \mat{Q} & \vb{0} \\ \vb{0}\T & 1 \end{bmatrix}\begin{bmatrix} \tilde{\mat{R}} \\ \mat{0} \\ \vb{w}\T \end{bmatrix}. Moving row w⊤\vb{w}\T immediately below R~\tilde{\mat{R}} and applying G\mat{G} are orthogonal transformations, leaving the matrix as (orthogonal) times [R~′0]\begin{bmatrix} \tilde{\mat{R}}' \\ \mat{0} \end{bmatrix}: a QR. Rotation kk mixes row kk of R~\tilde{\mat{R}}, which has zeros in columns 1,…,k−11, \dots, k - 1, with the new row, which already has them from earlier rotations; it creates no fill and operates only on columns k,…,n+1k, \dots, n + 1, using 6(n+2−k)6(n + 2 - k) flops. The last rotation acts on pair (ρ,γ)(\rho, \gamma) in column n+1n + 1 and converts it to (ρ2+γ2,0)(\sqrt{\rho^2 + \gamma^2}, 0).

∎

This is QR-form recursive least squares. With forgetting factor λ∈(0,1]\lambda \in (0, 1], multiply R~\tilde{\mat{R}} by λ\sqrt{\lambda} before each new observation, and the solution is weighted least squares with weights λt−i\lambda^{t - i}: the observation jj steps ago weighs λj\lambda^j and effective memory is about 1/(1−λ)1/(1 - \lambda) observations. It is natural for rolling factor regressions in factor regressions, and you implement it in the lab. Classical recursive least squares, which updates (A⊤A)−1(\mat{A}\T\mat{A})^{-1} using Sherman–Morrison, works with the normal-equations matrix and inherits its κ2\kappa^2; QR works with R\mat{R}, whose condition number is κ(A)\kappa(\mat{A}).

Hessenberg matrices and removing columns or rows

An upper Hessenberg matrix has zeros below the first subdiagonal: just one entry to zero per column. Its QR uses n−1n - 1 rotations of adjacent rows and O(n2)\bigO(n^2) flops. This step is repeated in every iteration of the QR eigenvalue algorithm, which works with Hessenberg matrices.

Removing a column produces a Hessenberg matrix. If column kk of R\mat{R} is deleted, later columns shift left and each retains an entry below the new diagonal: n−kn - k adjacent-row rotations restore triangular form. Backward variable selection and active-set methods need this operation. Adding a column a\vb{a} requires Q⊤a\mat{Q}\T\vb{a}, so reflectors or Q\mat{Q} must be retained; then a reflector or rotations zero its lower part.

Removing a row (for a fixed-size sliding window) is harder. Without Q\mat{Q}, it uses hyperbolic rotations, which are not orthogonal and can amplify errors when the removed row strongly influenced the solution; the problem is inherently worse conditioned because removing data can bring the matrix closer to rank deficiency. Björck (1996, chapter 3) analyzes alternatives. In practice either retain Q\mat{Q} (as scipy.linalg.qr_delete does), or use exponential forgetting, which only adds rows.

InteractiveGivens rotations one by one
Each step applies a Givens rotation to the two highlighted rows and zeros the marked entry. In Add a row, the matrix is R~\tilde{\mat{R}} for a quadratic regression with 12 observations, [A b][\mat{A}\ \vb{b}] with columns 1,x,x21, x, x^2 and bb, plus a new observation below. Four rotations, whose flop count you can compare with redoing QR on 13 observations, give new coefficients matching QR from scratch, and the bottom-right entry becomes the new residual norm. Also try Hessenberg (one rotation per column) and Remove a column (R without its second column is Hessenberg from there).

Least squares: three algorithms and a bound

Let A∈Rm×n\mat{A} \in \R^{m\times n} with m≥nm \ge n and rank nn. Numerical least squares has three standard algorithms:

AlgorithmStepsFlops (leading order)Order of relative error in x\vb{x} (bound)
Normal equationsG=A⊤A\mat{G} = \mat{A}\T\mat{A}, Cholesky G=LL⊤\mat{G} = \mat{L}\mat{L}\T, two substitutionsmn2+n3/3mn^2 + n^3/3≈uκ2\approx u\kappa^2 always
Householder QRA=QR\mat{A} = \mat{Q}\mat{R}, z=Q⊤b\vb{z} = \mat{Q}\T\vb{b}, Rx=z1:n\mat{R}\vb{x} = \vb{z}_{1:n}2mn2−2n3/32mn^2 - 2n^3/3≈u(κ+κ2tan⁡θ/η)\approx u(\kappa + \kappa^2\tan\theta/\eta)
SVDA=UΣV⊤\mat{A} = \mat{U}\mat{\Sigma}\mat{V}\T, x=VΣ−1U⊤b\vb{x} = \mat{V}\mat{\Sigma}^{-1}\mat{U}\T\vb{b}several times QRlike QR, also handles rank deficiency

For m≫nm \gg n normal equations cost half as much as Householder (A⊤A\mat{A}\T\mat{A} is symmetric, so only half is computed). This is their only advantage; its price is in the last column. To understand it, we need to know how data perturbations affect the problem.

This is theorem 18.1 of Trefethen and Bau. The key cell is the bottom right. If the residual is small (θ≈0\theta \approx 0), the problem’s condition number is ≈κ\approx \kappa, as for a square system. If not, κ2\kappa^2 appears, moderated by tan⁡θ/η\tan\theta/\eta: the problem itself becomes sensitive to the square of κ\kappa, which no algorithm can avoid. Since Householder QR is backward stable for least squares (Higham, chapter 20; Trefethen and Bau, lecture 19), its error is bounded by a modest multiple of uu times that condition number. Normal equations instead solve a system with matrix A⊤A\mat{A}\T\mat{A}, condition number κ2\kappa^2, even when θ=0\theta = 0: they lose twice as many digits as QR precisely when unnecessary.

[ ]Angle θ determines when κ² mattersBrowser
import numpy as np
import scipy.linalg as sl

def matriz_kappa(m, n, kappa, rng):
    """A = U diag(sigma) V^T con valores singulares de 1 a 1/kappa en progresión geométrica."""
    U, _ = np.linalg.qr(rng.standard_normal((m, n)))
    V, _ = np.linalg.qr(rng.standard_normal((n, n)))
    return (U * np.logspace(0, -np.log10(kappa), n)) @ V.T

def lstsq_normales(A, b):
    L = np.linalg.cholesky(A.T @ A)
    return sl.solve_triangular(L.T, sl.solve_triangular(L, A.T @ b, lower=True))

def lstsq_qr(A, b):
    Q, R = np.linalg.qr(A)                       # Householder de LAPACK
    return sl.solve_triangular(R, Q.T @ b)

rng = np.random.default_rng(2)
m, n, kappa, u = 60, 15, 1e6, 2.0**-53
A = matriz_kappa(m, n, kappa, rng)
x = rng.standard_normal(n)
y = A @ x
eta = np.linalg.norm(A, 2) * np.linalg.norm(x) / np.linalg.norm(y)
Qc, _ = np.linalg.qr(A, mode="complete")
r = Qc[:, n:] @ rng.standard_normal(m - n)
r /= np.linalg.norm(r)                           # dirección ortogonal a col(A)

E = rng.standard_normal((m, n))
E *= 1e-10 * np.linalg.norm(A, 2) / np.linalg.norm(E, 2)   # perturbación aleatoria de tamaño relativo 1e-10

print(f"kappa = {kappa:.0e}   eta = {eta:.1f}   kappa u = {kappa * u:.1e}   kappa^2 u = {kappa**2 * u:.1e}")
print(" tan(theta)   condición teórica   amplificación medida   error QR   error normales")
for tan in (0, 1e-8, 1e-6, 1e-4, 1e-2, 1):
    b = y + tan * np.linalg.norm(y) * r          # el residuo de x es exactamente tan(theta) ||y|| r
    cond = kappa + kappa**2 * tan / eta
    x_pert = np.linalg.lstsq(A + E, b, rcond=None)[0]
    amp = np.linalg.norm(x_pert - x) / np.linalg.norm(x) / 1e-10
    e_qr = np.linalg.norm(lstsq_qr(A, b) - x) / np.linalg.norm(x)
    e_ne = np.linalg.norm(lstsq_normales(A, b) - x) / np.linalg.norm(x)
    print(f"{tan:9.0e}      {cond:10.1e}          {amp:10.1e}        {e_qr:8.1e}    {e_ne:8.1e}")

# Läuchli: formar A^T A ya destruye la información
eps = 1e-8
L3 = np.array([[1, 1], [eps, 0], [0, eps]])
print("\nLäuchli, eps = 1e-8:  fl(A^T A) =", (L3.T @ L3).tolist(), "  rango", np.linalg.matrix_rank(L3.T @ L3), " frente a rango(A) =", np.linalg.matrix_rank(L3))

The table separates problem from algorithm. The first two numerical columns concern the problem: theoretical conditioning and amplification measured by randomly perturbing A\mat{A} by one part in 101010^{10} and solving with lstsq. Random perturbation is not worst-case and amplifies 12 to 14 times less than the bound, but follows exactly the same law: constant (7×1047\times 10^4) while κ\kappa dominates, and proportional to tan⁡θ\tan\theta once κ2tan⁡θ/η\kappa^2\tan\theta/\eta exceeds it, which with η≈19\eta \approx 19 happens near tan⁡θ≈2×10−5\tan\theta \approx 2\times 10^{-5}. With tan⁡θ=1\tan\theta = 1, relative data error 10−1010^{-10} causes error 0.440.44 in x\vb{x}, whatever the algorithm. The last two columns concern algorithms with exact data: QR stays between 1.5×10−121.5\times 10^{-12} and 4×10−124\times 10^{-12} throughout, below κu≈10−10\kappa u \approx 10^{-10} (backward stability guarantees a bound, and QR’s equivalent perturbation need not point in the worst direction); normal equations give 1.4×10−51.4\times 10^{-5} from the first row, the κ2u≈10−4\kappa^2 u \approx 10^{-4} level, although the problem with θ=0\theta = 0 would justify only 10−1010^{-10}. They are never more accurate than QR; at best they match in order of magnitude when the residual is so large that κ2\kappa^2 governs the problem itself.

The last line is Läuchli’s example: A=[11ε00ε]\mat{A} = \begin{bmatrix} 1 & 1 \\ \eps & 0 \\ 0 & \eps \end{bmatrix} has rank 2 and κ≈2/ε\kappa \approx \sqrt{2}/\eps, but A⊤A=[1+ε2111+ε2]\mat{A}\T\mat{A} = \begin{bmatrix} 1 + \eps^2 & 1 \\ 1 & 1 + \eps^2 \end{bmatrix} and, with ε=10−8\eps = 10^{-8}, 1+ε21 + \eps^2 rounds to 1: the computed matrix is exactly singular. Information was present in the data and lost in the first product. No later algorithm, however good, can recover it.

InteractiveNormal equations versus QR
The 40 observations from the motivation and least-squares polynomials computed in your browser using normal equations, Householder QR and SVD. Change degree with t∈[1,2]t \in [1, 2]: from degree 7, κ(X)2\kappa(\mat{X})^2 approaches 1/u1/u and normal-equation coefficients deteriorate; from degree 8 they retain no digits and their residual is no longer minimal, although the curve differs by only hundredths. Switch to t∈[−1,1]t \in [-1, 1]: the same polynomials are written in another variable and the exact fit is the same curve, but at degree 9 κ(X)\kappa(\mat{X}) falls from 6×10106\times 10^{10} to 10310^3 and all three solutions agree through degree 20. With t∈[1,2]t \in [1, 2] and degree 15 or higher, κ(X)\kappa(\mat{X}) exceeds 1/u1/u: the matrix is numerically rank deficient, lstsq's cutoff discards singular values and even QR and SVD disagree.

The interactive shows two separate things. First, the theorem: with the same matrix, normal equations fail where QR does not. Second, κ(X)\kappa(\mat{X}) depends on how the model is written. Columns tjt^j with t∈[1,2]t \in [1, 2] are nearly parallel (all grow similarly over the interval); centering and scaling the variable to [−1,1][-1, 1] separates them, and an orthogonal basis such as Chebyshev separates them further. For variables on different scales, the minimum remedy is column scaling: a theorem of van der Sluis (1969) says dividing each column by its norm puts κ2(AD)\kappa_2(\mat{A}\mat{D}) within factor n\sqrt{n} of the minimum across diagonal scalings D\mat{D}. A variable in euros (of order 10610^6) alongside another in unit fractions can multiply κ\kappa by a factor of order 10610^6 without changing the statistical problem.

Rank deficiency

If A\mat{A} has rank r<nr < n, least squares has infinitely many solutions, all those of x0+null⁡(A)\vb{x}_0 + \nullsp(\mat{A}), and R\mat{R} has zeros on its diagonal. In floating point these zeros appear as small numbers, and the question changes from “what is the rank?” to “which singular values are noise?”. The numerical rank at tolerance τ\tau is the number of singular values greater than τ\tau, and it gives two tools.

Column-pivoted QR

Column-pivoted QR (Businger and Golub, 1965) selects at each step the remaining column with greatest active-row norm, swaps it into position kk and applies the reflector:

AΠ=QR,∣r11∣≥∣r22∣≥⋯≥∣rnn∣.\mat{A}\mat{\Pi} = \mat{Q}\mat{R}, \qquad \abs{r_{11}} \ge \abs{r_{22}} \ge \cdots \ge \abs{r_{nn}}.

Remaining column norms are updated instead of recomputed, subtracting the square of the entry just moved to row kk, ∥aj(k+1)∥2=∥aj(k)∥2−rkj2\norm{\vb{a}_j^{(k+1)}}^2 = \norm{\vb{a}_j^{(k)}}^2 - r_{kj}^2, and recomputing when subtraction cancels too much (LAPACK routine geqp3 does this). Extra cost over unpivoted QR is of order mnmn.

Proof

Q\mat{Q} and Π\mat{\Pi} are orthogonal, so A\mat{A} and R\mat{R} have the same singular values. For the first inequality, the first kk columns of R\mat{R} form [R110]\begin{bmatrix} \mat{R}_{11} \\ \mat{0} \end{bmatrix}, with the same singular values as R11\mat{R}_{11}, and removing columns does not increase singular values (interlacing): σk(R11)≤σk(R)\sigma_k(\mat{R}_{11}) \le \sigma_k(\mat{R}). For the second, zeroing R22\mat{R}_{22} yields a matrix of rank at most kk at distance ∥R22∥2\norm{\mat{R}_{22}}_2 from R\mat{R}; by the Eckart–Young theorem, no rank-≤k\le k matrix is closer to R\mat{R} than σk+1(R)\sigma_{k+1}(\mat{R}).

∎

If ∥R22∥\norm{\mat{R}_{22}} is small, the matrix is near one of rank kk; any permutation guarantees that. Pivoting does not guarantee the reverse: that large R22\mat{R}_{22} or ∣rkk∣\abs{r_{kk}} implies large σk+1\sigma_{k+1}. Kahan’s matrix is the classic counterexample: with LAPACK column pivoting (and minimal rescaling of its columns, all of norm 1, to break ties), all ∣rkk∣\abs{r_{kk}} are moderate yet the matrix is nearly singular. You will see it in the lab. Algorithms guarantee both directions (the “strong” rank-revealing QR of Gu and Eisenstat, 1996), but simple pivoting almost never fails in practice, making it the usual inexpensive numerical-rank estimate.

The minimum-norm solution

With pivoted QR and numerical rank kk, the most direct solution discards R22\mat{R}_{22} and solves R11xB=(Q⊤b)1:k\mat{R}_{11}\vb{x}_B = (\mat{Q}\T\vb{b})_{1:k}, setting the remaining n−kn - k variables to zero. This is the basic solution: it uses only kk columns of A\mat{A}, chosen by pivoting. It is not the minimum-norm solution and changes when column scales change.

The solution independent of these choices is the minimum-norm solution x†=A+b\vb{x}^\dagger = \mat{A}\pinv\vb{b}, which with SVD A=∑iσiuivi⊤\mat{A} = \sum_i \sigma_i\vb{u}_i\vb{v}_i\T and a tolerance gives the truncated SVD:

xk=∑i=1kui⊤bσi vi,k=#{i:σi>τ σ1}.\vb{x}_k = \sum_{i=1}^{k} \frac{\vb{u}_i\T\vb{b}}{\sigma_i}\,\vb{v}_i, \qquad k = \#\{i : \sigma_i > \tau\,\sigma_1\}.

This is the heart of rank-deficient least squares: the result depends on tolerance, which data should determine. Suppose b=Ax⋆+δe\vb{b} = \mat{A}\vb{x}_\star + \delta\vb{e}, with noise of size δ\delta per component. Then ui⊤b=σi(vi⊤x⋆)+δ ui⊤e\vb{u}_i\T\vb{b} = \sigma_i(\vb{v}_i\T\vb{x}_\star) + \delta\,\vb{u}_i\T\vb{e} and

xk−x⋆=∑i=1kδ ui⊤eσivi⏟ruido amplificado−∑i>k(vi⊤x⋆) vi⏟sesgo por truncar.\vb{x}_k - \vb{x}_\star = \underbrace{\sum_{i=1}^{k}\frac{\delta\,\vb{u}_i\T\vb{e}}{\sigma_i}\vb{v}_i}_{\text{ruido amplificado}} - \underbrace{\sum_{i>k}(\vb{v}_i\T\vb{x}_\star)\,\vb{v}_i}_{\text{sesgo por truncar}} .

Keeping term ii adds noise of size δ/σi\delta/\sigma_i; discarding it loses ∣vi⊤x⋆∣\abs{\vb{v}_i\T\vb{x}_\star}. It is worthwhile to keep it while σi\sigma_i exceeds δ/∣vi⊤x⋆∣\delta/\abs{\vb{v}_i\T\vb{x}_\star}, meaning signal σi∣vi⊤x⋆∣\sigma_i\abs{\vb{v}_i\T\vb{x}_\star} exceeds noise δ\delta. The default relative tolerance of np.linalg.lstsq, εmax⁡(m,n)≈10−14\eps\max(m, n) \approx 10^{-14}, is designed for machine rounding, not measurement noise, and if δ\delta is larger it lets through terms that are merely noise multiplied by 1/σi1/\sigma_i.

InteractiveTolerance versus noise
A problem with singular values from 1 to 10−1210^{-12} and a true solution with the same component along each vi\vb{v}_i. Left, the Picard plot: σi\sigma_i, coefficients ∣ui⊤b∣\abs{\vb{u}_i\T\vb{b}}, and ratios ∣ui⊤b∣/σi\abs{\vb{u}_i\T\vb{b}}/\sigma_i entering the solution. While signal dominates, ∣ui⊤b∣\abs{\vb{u}_i\T\vb{b}} falls with σi\sigma_i and the ratio stays steady; when ∣ui⊤b∣\abs{\vb{u}_i\T\vb{b}} hits the noise floor δ\delta, the ratio shoots up. Right, truncated SVD error versus tolerance, with lstsq's default cutoff marked. Start there and raise it until the horizontal line reaches the noise; then change δ\delta and see how the best cutoff moves.

Initially δ=10−6\delta = 10^{-6} and tolerance is lstsq’s default: all 10 singular values are kept. Since signal in direction ii is σi/10\sigma_i/\sqrt{10}, the last five (with σi\sigma_i from 2×10−72\times 10^{-7} to 10−1210^{-12}) are below noise, and relative solution error is 2.2×1052.2\times 10^{5}. A cutoff at the noise level (rank 5) reduces it to 0.720.72. It does not reach zero: half the true solution lies in directions hidden by noise, and no algorithm can recover it from these data; the only option is not to invent it. No tolerance fits every problem: the right one depends on δ\delta, so rcond requires thought, not just a technical setting. Ridge regularization, covered in ridge spectral shrinkage, replaces the hard cutoff with smooth factor σi2/(σi2+λ)\sigma_i^2/(\sigma_i^2 + \lambda).

Implementation from scratch

The first lab implements the three Gram–Schmidt variants and Householder QR with reflectors in LAPACK format, and checks that the latter reproduces LAPACK’s output.

[ ]Three Gram–Schmidt variants and HouseholderBrowser
import numpy as np

def cgs(A):
    """Gram-Schmidt clásico: todas las sombras de a_k se calculan con el vector 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]
        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 (por filas de R): q_k se resta de todas las columnas en cuanto se conoce."""
    Q = np.array(A, dtype=float)
    n = Q.shape[1]
    R = np.zeros((n, n))
    for k in range(n):
        R[k, k] = np.linalg.norm(Q[:, k])
        Q[:, k] /= R[k, k]
        R[k, k + 1:] = Q[:, k] @ Q[:, k + 1:]
        Q[:, k + 1:] -= np.outer(Q[:, k], R[k, k + 1:])
    return Q, R

def cgs2(A):
    """Gram-Schmidt clásico con reortogonalización: cada proyección se hace dos veces."""
    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):
        v = A[:, k].copy()
        for _ in range(2):
            h = Q[:, :k].T @ v
            v -= Q[:, :k] @ h
            R[:k, k] += h
        R[k, k] = np.linalg.norm(v)
        Q[:, k] = v / R[k, k]
    return Q, R

def householder_qr(A):
    """QR de Householder en el formato de LAPACK (geqrf): R en el triángulo superior y, bajo la
    diagonal de la columna k, el reflector v_k sin su primera entrada (que vale 1); H_k = I - tau_k v_k v_k^T."""
    QR = np.array(A, dtype=float)
    m, n = QR.shape
    tau = np.zeros(n)
    for k in range(min(m - 1, n)):
        alpha, x = QR[k, k], QR[k + 1:, k]
        sigma = np.linalg.norm(x)
        if sigma == 0.0:                                     # nada que anular: H_k = I
            continue
        beta = -np.copysign(np.hypot(alpha, sigma), alpha)    # destino -sign(x1) ||x|| e1
        tau[k] = (beta - alpha) / beta
        QR[k + 1:, k] = x / (alpha - beta)                   # alpha - beta: mismo signo, no cancela
        QR[k, k] = beta
        v = QR[k + 1:, k]
        w = QR[k, k + 1:] + v @ QR[k + 1:, k + 1:]           # w = v^T A[k:, k+1:] con v[0] = 1
        QR[k, k + 1:] -= tau[k] * w
        QR[k + 1:, k + 1:] -= tau[k] * np.outer(v, w)
    return QR, tau

def apply_qt(QR, tau, b):
    """Q^T b = H_n ... H_1 b sin formar Q: unos 4mn flops."""
    b = np.array(b, dtype=float)
    for k in range(len(tau)):
        if tau[k] != 0.0:
            v = np.concatenate(([1.0], QR[k + 1:, k]))
            b[k:] -= tau[k] * v * (v @ b[k:])
    return b

def form_q(QR, tau):
    """Q delgada (m x n) por acumulación hacia atrás: Q = H_1 (H_2 (... H_n [I; 0]))."""
    m, n = QR.shape
    Q = np.eye(m, n)
    for k in reversed(range(len(tau))):
        if tau[k] != 0.0:
            v = np.concatenate(([1.0], QR[k + 1:, k]))
            Q[k:, k:] -= tau[k] * np.outer(v, v @ Q[k:, k:])
    return Q

rng = np.random.default_rng(0)
A = rng.standard_normal((7, 4))
QR, tau = householder_qr(A)
h, tau_lapack = np.linalg.qr(A, mode="raw")                  # LAPACK, en orden de Fortran
print("mismos reflectores, R y tau que LAPACK:", np.allclose(QR, h.T), np.allclose(tau, tau_lapack))
print("tau en [1, 2]:", np.round(tau, 4))
Q, R = form_q(QR, tau), np.triu(QR[:4])
b = rng.standard_normal(7)
print(f"||A - QR|| = {np.linalg.norm(A - Q @ R):.1e}   ||I - Q^T Q|| = {np.linalg.norm(np.eye(4) - Q.T @ Q):.1e}")
print("Q^T b sin formar Q coincide:", np.allclose(apply_qt(QR, tau, b)[:4], Q.T @ b))

The first three functions differ in two lines. In cgs, all coefficients of column kk come from A[:, k], the original vector; in mgs the loop is organized by rows of R\mat{R}: once qk\vb{q}_k is normalized, its projection is subtracted from every later column, which reaches its turn already cleared of earlier directions. householder_qr reproduces LAPACK’s format bit for bit, as comparison with mode="raw" confirms, and τk\tau_k fall in [1,2][1, 2] as the formula predicts.

Now the measurement summarizing this section: orthogonality of each Q^\hat{\mat{Q}} against κ\kappa, with the same matrix model as the interactive.

[ ]Orthogonality versus κBrowser
import numpy as np
import matplotlib.pyplot as plt

def matriz_kappa(m, n, kappa, rng):
    U, _ = np.linalg.qr(rng.standard_normal((m, n)))
    V, _ = np.linalg.qr(rng.standard_normal((n, n)))
    return (U * np.logspace(0, -np.log10(kappa), n)) @ V.T

rng = np.random.default_rng(0)
m, n, u = 60, 15, 2.0**-53
I = np.eye(n)
exps = np.arange(0, 17, 2)
perdida = {"CGS": [], "MGS": [], "CGS2": [], "Householder": []}
print(" kappa       CGS       MGS      CGS2   Householder   peor ||A-QR||/||A||")
for e in exps:
    A = matriz_kappa(m, n, 10.0**e, rng)
    QR, tau = householder_qr(A)
    fact = {"CGS": cgs(A), "MGS": mgs(A), "CGS2": cgs2(A), "Householder": (form_q(QR, tau), np.triu(QR[:n]))}
    peor = 0.0
    for nombre, (Q, R) in fact.items():
        perdida[nombre].append(np.linalg.norm(I - Q.T @ Q, 2))
        peor = max(peor, np.linalg.norm(A - Q @ R, 2) / np.linalg.norm(A, 2))
    print(f"1e{e:<4d}" + "".join(f"{perdida[k][-1]:10.1e}" for k in perdida) + f"      {peor:.1e}")

for nombre in ("CGS", "MGS"):
    p = np.array(perdida[nombre])
    ok = (p > 1e-14) & (p < 1e-2)                      # tramo entre el suelo u y la saturación
    print(f"pendiente de {nombre} en escala log-log: {np.polyfit(exps[ok], np.log10(p[ok]), 1)[0]:.2f}")

k = 10.0**exps
for nombre, marca in zip(perdida, "os^d"):
    plt.loglog(k, perdida[nombre], marca + "-", label=nombre)
plt.loglog(k, u * k**2, "k:", label="uκ²")
plt.loglog(k, u * k, "k--", label="uκ")
plt.ylim(1e-17, 1e2); plt.xlabel("κ₂(A)"); plt.ylabel("‖I − QᵀQ‖₂"); plt.legend(); plt.show()

The measured slopes match the theorem: 1.861.86 for CGS (near 2: the theorem’s constant is not uniform across the range) and 1.021.02 for MGS. With κ=108\kappa = 10^8, CGS’s Q^\hat{\mat{Q}} has ∥I−Q^⊤Q^∥≈3×10−2\norm{\mat{I} - \hat{\mat{Q}}\T\hat{\mat{Q}}} \approx 3\times 10^{-2}; with 101010^{10} it is 3, no longer orthogonal to any digit, and beyond that saturates between 3 and 7. MGS retains 2×10−92\times 10^{-9} with κ=108\kappa = 10^8, about 8 digits. CGS2 and Householder never exceed 1.1×10−151.1\times 10^{-15}, even at κ=1016\kappa = 10^{16}, where CGS2’s assumptions no longer hold and theory guarantees nothing. The last column is most often forgotten: all four factorizations reconstruct A\mat{A} with error of order uu. Looking only at ∥A−Q^R^∥\norm{\mat{A} - \hat{\mat{Q}}\hat{\mat{R}}} never warns that Q^\hat{\mat{Q}} is not orthogonal.

Finally, least squares with the lesson’s algorithms and two library routines, for zero-residual problems where a stable method’s error should be of order uκu\kappa.

[ ]Least squares: six waysBrowser
import numpy as np
import scipy.linalg as sl

def lstsq_householder(A, b):
    QR, tau = householder_qr(A)
    n = A.shape[1]
    return sl.solve_triangular(QR[:n], apply_qt(QR, tau, b)[:n])        # solve_triangular mira solo el triángulo superior

def lstsq_mgs(A, b):                     # MGS y después Q^T b con la Q calculada
    Q, R = mgs(A)
    return sl.solve_triangular(R, Q.T @ b)

def lstsq_mgs_ampliada(A, b):            # MGS sobre [A b]: la última columna de R es Q^T b
    n = A.shape[1]
    _, R = mgs(np.column_stack([A, b]))
    return sl.solve_triangular(R[:n, :n], R[:n, n])

def lstsq_scipy_qr(A, b):
    Q, R = sl.qr(A, mode="economic")
    return sl.solve_triangular(R, Q.T @ b)

metodos = {"normales": lstsq_normales, "MGS, Q^T b": lstsq_mgs, "MGS [A b]": lstsq_mgs_ampliada,
           "Householder": lstsq_householder, "scipy qr": lstsq_scipy_qr,
           "np lstsq": lambda A, b: np.linalg.lstsq(A, b, rcond=None)[0]}
rng = np.random.default_rng(1)
m, n, u = 60, 15, 2.0**-53
print("kappa " + "".join(f"{k:>13s}" for k in metodos) + "   u*kappa")
for e in (2, 4, 6, 8, 10, 12):
    A = matriz_kappa(m, n, 10.0**e, rng)
    x = rng.standard_normal(n)
    b = A @ x                                         # residuo nulo: theta = 0
    errores = []
    for f in metodos.values():
        try:
            errores.append(np.linalg.norm(f(A, b) - x) / np.linalg.norm(x))
        except (np.linalg.LinAlgError, ValueError):
            errores.append(np.nan)                    # Cholesky falla o devuelve NaN
    print(f"1e{e:<4d}" + "".join(f"{v:13.1e}" for v in errores) + f"   {10.0**e * u:.0e}")

Four of six columns stay below the last, uκu\kappa: Householder (ours), SciPy QR, lstsq and MGS applied to [A b][\mat{A}\ \vb{b}]. The other two diverge: normal equations have error ≈5×10−2\approx 5\times 10^{-2} with κ=108\kappa = 10^{8} and from 101010^{10} Cholesky does not even finish (nan); MGS with Q^⊤b\hat{\mat{Q}}\T\vb{b} is just as bad (6×10−26\times 10^{-2} with κ=108\kappa = 10^8), and with κ=1012\kappa = 10^{12} gives error 5×1055\times 10^{5}, no correct digits. The difference between columns two and three is Björck and Paige’s result: the same algorithm, the same poorly orthogonal Q^\hat{\mat{Q}}, only where Q⊤b\mat{Q}\T\vb{b} is computed changes.

Lab: online regression and rank deficiency

The second lab applies row updates to a rolling factor regression and studies nearly collinear columns. The series is synthetic with an explicit model: daily asset return is 0.0002+βt ftmkt+0.3 fttam−0.2 ftval+εt0.0002 + \beta_t\,f^{\text{mkt}}_t + 0.3\,f^{\text{tam}}_t - 0.2\,f^{\text{val}}_t + \varepsilon_t, with three independent Gaussian factors and a market beta changing regime halfway through the sample. Regression uses exponential forgetting with λ=0.98\lambda = 0.98, an effective memory of about 50 days.

[ ]Online regression with GivensBrowser
import numpy as np
import scipy.linalg as sl
import matplotlib.pyplot as plt

def givens(a, b):
    """(c, s, r) con [c s; -s c] [a; b] = [r; 0] y r = hypot(a, b) >= 0."""
    if b == 0.0:
        return (1.0, 0.0, a) if a >= 0 else (-1.0, 0.0, -a)
    r = np.hypot(a, b)
    return a / r, b / r, r

def anadir_fila(Rt, fila, lam=1.0):
    """Rt: triangular (n+1) x (n+1) de [A b]. Devuelve la de [sqrt(lam) [A b]; fila]: unos 3n^2 flops."""
    Rt = np.sqrt(lam) * Rt                         # olvido exponencial
    w = np.array(fila, dtype=float)
    for k in range(len(w)):
        c, s, r = givens(Rt[k, k], w[k])
        fila_k = Rt[k, k + 1:].copy()
        Rt[k, k] = r
        Rt[k, k + 1:] = c * fila_k + s * w[k + 1:]
        w[k + 1:] = -s * fila_k + c * w[k + 1:]
        w[k] = 0.0
    return Rt

def resolver(Rt):
    """Coeficientes y norma del residuo (ponderado) a partir de la R de [A b]."""
    n = Rt.shape[0] - 1
    return sl.solve_triangular(Rt[:n, :n], Rt[:n, n]), abs(Rt[n, n])

rng = np.random.default_rng(7)
T = 750
F = rng.standard_normal((T, 3)) * np.array([0.010, 0.006, 0.005])      # mercado, tamaño, valor
dias = np.arange(T)
beta_mkt = 0.8 + 0.6 * (dias > 375) + 0.1 * np.sin(dias / 40)
r = 0.0002 + beta_mkt * F[:, 0] + 0.3 * F[:, 1] - 0.2 * F[:, 2] + 0.004 * rng.standard_normal(T)
X = np.column_stack([np.ones(T), F])
lam = 0.98

Rt = np.zeros((5, 5))
betas, dif = np.full(T, np.nan), 0.0
for t in range(T):
    Rt = anadir_fila(Rt, np.append(X[t], r[t]), lam)
    if t >= 4:
        coef, rho = resolver(Rt)
        betas[t] = coef[1]
        if t % 50 == 0 or t == T - 1:              # comprobación: mínimos cuadrados ponderados desde cero
            w = np.sqrt(lam ** (t - dias[:t + 1]))
            ref = np.linalg.lstsq(w[:, None] * X[:t + 1], w * r[:t + 1], rcond=None)[0]
            dif = max(dif, np.linalg.norm(coef - ref) / np.linalg.norm(ref))
print(f"máxima diferencia relativa con lstsq rehecho desde cero: {dif:.1e}")
for t in (300, 450, 700):
    print(f"t = {t}: beta estimada {betas[t]:.3f}, verdadera {beta_mkt[t]:.3f}")

plt.plot(dias, beta_mkt, color="gray", label="beta verdadera")
plt.plot(dias, betas, label="estimación en línea (λ = 0.98)")
plt.ylim(0, 2); plt.xlabel("día"); plt.ylabel("beta de mercado"); plt.legend(); plt.show()

Rotation updates agree with weighted least squares recomputed from scratch to relative 3×10−153\times 10^{-15}, and each step costs the same on day 10 as day 700: the entire state is an 5×55\times 5 matrix. The graph shows the statistical tradeoff of forgetting: with 50 days’ memory the estimate is noisy (on day 300 it is 0.8490.849 versus true beta 0.8940.894) and adapts slowly to the day-376 jump: on day 450 it is still 1.2251.225 versus 1.3031.303. A larger λ\lambda smooths it and slows adaptation. This tradeoff is statistical; the algebra is exact for any λ\lambda.

Now rank deficiency: six variables, two nearly linear combinations of the others, with deviations of size 10−610^{-6} and 10−1010^{-10}, and responses with noise of size 10−310^{-3}.

[ ]Nearly collinear columns: pivoting, tolerance and KahanBrowser
import numpy as np
import scipy.linalg as sl

rng = np.random.default_rng(3)
m = 200
Z = rng.standard_normal((m, 4))
X = np.column_stack([Z,
                     0.5 * Z[:, 0] + 0.5 * Z[:, 1] + 1e-6 * rng.standard_normal(m),   # x5 casi (x1 + x2)/2
                     Z[:, 2] - Z[:, 3] + 1e-10 * rng.standard_normal(m)])           # x6 casi x3 - x4
beta = np.array([1.0, -1.0, 0.5, 2.0, 0.0, 0.0])
ruido = 1e-3
y = X @ beta + ruido * rng.standard_normal(m)

Q, R, piv = sl.qr(X, mode="economic", pivoting=True)
print("orden de las columnas elegido por el pivoteo (desde 1):", piv + 1)
print("|r_kk|:            ", np.array2string(np.abs(np.diag(R)), precision=1))
print("valores singulares:", np.array2string(np.linalg.svd(X, compute_uv=False), precision=1))

def tsvd(X, y, tol):
    """Solución de norma mínima descartando los sigma_i <= tol * sigma_1."""
    U, s, Vt = np.linalg.svd(X, full_matrices=False)
    k = int(np.sum(s > tol * s[0]))
    return Vt[:k].T @ ((U[:, :k].T @ y) / s[:k]), k

y2 = X @ beta + ruido * rng.standard_normal(m)      # otra realización del ruido
print("\n tolerancia  rango    ||x||     residuo   cambio de x con otro ruido")
for tol in (np.finfo(float).eps * m, 1e-12, 1e-8, 1e-5, 1e-2):
    x1, k = tsvd(X, y, tol)
    x2, _ = tsvd(X, y2, tol)
    print(f"{tol:9.1e}    {k}   {np.linalg.norm(x1):9.3g}  {np.linalg.norm(X @ x1 - y):9.4f}   {np.linalg.norm(x1 - x2):9.3g}")

k = 4
xb = np.zeros(6)
xb[piv[:k]] = sl.solve_triangular(R[:k, :k], Q[:, :k].T @ y)
xm, _ = tsvd(X, y, 1e-5)
print("\nsolución básica (QR pivotada, rango 4):", np.round(xb, 3), f"  norma {np.linalg.norm(xb):.3f}")
print("solución de norma mínima (SVD):        ", np.round(xm, 3), f"  norma {np.linalg.norm(xm):.3f}")

# la matriz de Kahan: el pivoteo de columnas no ve que es casi singular
n, c = 90, 0.285
s_ = np.sqrt(1 - c * c)
K = np.diag(s_ ** np.arange(n)) @ (np.eye(n) - c * np.triu(np.ones((n, n)), 1))
K = K @ np.diag((1 - 1e-12) ** np.arange(n))        # rompe los empates de normas: el pivoteo no permuta
_, RK, pK = sl.qr(K, pivoting=True)
sK = np.linalg.svd(K, compute_uv=False)
print(f"\nKahan {n}x{n}: sin permutar: {np.all(pK == np.arange(n))}   min |r_kk| = {np.abs(np.diag(RK)).min():.2e}   sigma_min = {sK[-1]:.2e}")

Read the output from top to bottom:

  • Pivoting reveals rank. The first four ∣rkk∣\abs{r_{kk}} are of order 10, and the last two, 1.4×10−51.4\times 10^{-5} and 1.3×10−91.3\times 10^{-9}, are of the order of the two small singular values (1.2×10−51.2\times 10^{-5} and 7.5×10−107.5\times 10^{-10}). The diagonal of R\mat{R} tracks singular values much more cheaply than SVD. Note which columns it leaves last: 5 and 3. It does not identify “the culprits” x5,x6x_5, x_6; it picks one well-conditioned set of four columns among several possibilities.
  • Default tolerance does not suit noisy data. With εm≈4×10−14\eps m \approx 4\times 10^{-14} all six singular values are retained and solution norm is 2×1052\times 10^{5} (the true norm is 2.52.5): noise 10−310^{-3} divided by σ6≈7.5×10−10\sigma_6 \approx 7.5\times 10^{-10}. It is unstable: another noise realization changes it by 5×1055\times 10^{5}. Meanwhile the residual is the same in every row, 0.01290.0129 or 0.0130.013: it cannot distinguish a sensible solution from an absurd one. With tolerances between 10−510^{-5} and 10−210^{-2}, above relative noise, rank is 4 and solution change between realizations is 10−410^{-4}.
  • Basic is not minimum norm. Both rank-4 solutions fit equally well, but the basic one uses pivot-selected columns and has norm 2.92.9; minimum norm spreads weight over collinear columns and has norm 2.32.3.
  • Pivoting can fail. In Kahan’s 90×9090\times 90 matrix, pivoting makes no swaps and the smallest ∣rkk∣\abs{r_{kk}} is 2.3×10−22.3\times 10^{-2}, while σmin⁡≈8.8×10−12\sigma_{\min} \approx 8.8\times 10^{-12}. A rule like “rank =#{∣rkk∣>τ}= \#\{\abs{r_{kk}} > \tau\}” would call the matrix full rank and well conditioned. This is deliberately constructed, but remember pivoted QR is a very reliable heuristic, not a two-way theorem.

In libraries

FunctionWhat it does
np.linalg.qr(A)Thin Householder QR (geqrf + orgqr). mode="r" only R\mat{R}; mode="complete" Q\mat{Q} of m×mm\times m; mode="raw" reflectors and τ\tau, like your householder_qr
scipy.linalg.qr(A, pivoting=True)Column-pivoted QR (geqp3); returns permutation as an index vector
scipy.linalg.qr_multiply(A, c)factors and multiplies by Q\mat{Q} or Q⊤\mat{Q}\T without forming it
scipy.linalg.qr_insert, qr_delete, qr_updateupdates with Givens rotations; need Q\mat{Q} and R\mat{R}
np.linalg.lstsq(A, b, rcond=None)SVD (gelsd) with cutoff at σi≤\sigma_i \le rcond ⋅ σ1\cdot\,\sigma_1; default rcond =εmax⁡(m,n)= \eps\max(m, n)
scipy.linalg.lstsq(A, b, cond, lapack_driver)gelsd (divide-and-conquer SVD, default), gelss (classical SVD) or gelsy (pivoted QR with complete orthogonal factorization)
[ ]QR and least squares in NumPy and SciPyBrowser
import numpy as np
import scipy
import scipy.linalg as sl

print("NumPy", np.__version__, "  SciPy", scipy.__version__)
A = np.random.default_rng(0).standard_normal((1000, 5))
b = np.ones(1000)
print("formas de np.linalg.qr:", [M.shape for M in np.linalg.qr(A)], " mode='r':", np.linalg.qr(A, mode="r").shape,
      " mode='raw':", [M.shape for M in np.linalg.qr(A, mode="raw")])

qtb_t, R = sl.qr_multiply(A, b, mode="right")    # devuelve b^T Q (Q delgada) sin formar Q
Q, _ = np.linalg.qr(A)
print("qr_multiply da Q^T b sin formar Q:", np.allclose(qtb_t, Q.T @ b))

Qf, Rf = sl.qr(A[:999])                            # Q completa de 999 x 999
Q2, R2 = sl.qr_insert(Qf, Rf, A[999], 999, which="row")
print("qr_insert de una fila reproduce A:", np.allclose(Q2 @ R2, A))

# el problema casi colineal del laboratorio: tolerancias y drivers
x_def, _, rk_def, _ = np.linalg.lstsq(X, y, rcond=None)
x_tol, _, rk_tol, _ = np.linalg.lstsq(X, y, rcond=1e-5)
print(f"\nnp.linalg.lstsq por defecto: rango {rk_def}, ||x|| = {np.linalg.norm(x_def):.3g}")
print(f"np.linalg.lstsq rcond=1e-5:  rango {rk_tol}, ||x|| = {np.linalg.norm(x_tol):.3g}")
for drv in ("gelsd", "gelss", "gelsy"):
    x, _, rk, _ = sl.lstsq(X, y, cond=1e-5, lapack_driver=drv)
    print(f"scipy lstsq {drv}: rango {rk}, distancia a la SVD truncada {np.linalg.norm(x - xm):.1e}")

All three SciPy drivers give the minimum-norm solution at the same tolerance: gelsd and gelss match truncated SVD to uu, and gelsy, which does not compute singular values, reproduces it to 4×10−114\times 10^{-11} because its complete orthogonal factorization AΠ=Q[T11000]Z⊤\mat{A}\mat{\Pi} = \mat{Q}\begin{bmatrix} \mat{T}_{11} & \mat{0} \\ \mat{0} & \mat{0} \end{bmatrix}\mat{Z}\T also yields minimum norm. gelsy is usually fastest; gelsd most robust. None chooses the tolerance for you.

Common mistakes

Exercises

NumericDigits surviving normal equations
A design matrix has κ2(A)=106\kappa_2(\mat{A}) = 10^6 and the problem's residual is small. You solve least squares with normal equations and Cholesky in float64 (u≈1.1×10−16u \approx 1.1\times 10^{-16}). At most how many correct decimal digits can you expect in the solution?
NumericCondition number with a residual
In a least-squares problem, κ2(A)=106\kappa_2(\mat{A}) = 10^6, the angle between b\vb{b} and col⁡(A)\col(\mat{A}) satisfies tan⁡θ=10−3\tan\theta = 10^{-3}, and η=∥A∥∥x∥/∥Ax∥=10\eta = \norm{\mat{A}}\norm{\vb{x}}/\norm{\mat{A}\vb{x}} = 10. What is the relative condition number of x\vb{x} with respect to perturbations of A\mat{A}?
QuizSame numbers, different rounding
Classical and modified Gram–Schmidt produce the same Q\mat{Q} in exact arithmetic. Why not in floating point?
QuizMGS for least squares
You computed the QR of A\mat{A} with κ2(A)=109\kappa_2(\mat{A}) = 10^{9} by MGS and want to solve min⁡∥Ax−b∥\min\norm{\mat{A}\vb{x} - \vb{b}} with a small residual. What do you do?
QuizWhich tolerance?
You fit a linear model with 5 variables to m=200m = 200 measurements with about 4 significant digits (relative error ≈10−4\approx 10^{-4}). The design matrix's relative singular values, σi/σ1\sigma_i/\sigma_1, are 1, 0.3, 2×10−2, 3×10−7, 10−131,\ 0.3,\ 2\times 10^{-2},\ 3\times 10^{-7},\ 10^{-13}. What rank would you use for the minimum-norm solution?
QuizWhen are normal equations reasonable?
In which case is it reasonable to solve least squares with normal equations and float64 Cholesky?
ProofThe reflector's sign
Prove: Let x∈Rm\vb{x} \in \R^m with x1>0x_1 > 0, σ=∥x∥\sigma = \norm{\vb{x}} and θ\theta the angle between x\vb{x} and e1\vb{e}_1. Suppose σ\sigma is computed as σ^=σ(1+δ1)\hat\sigma = \sigma(1 + \delta_1), ∣δ1∣≤cu\abs{\delta_1} \le cu, and each addition or subtraction introduces a factor (1+δ)(1 + \delta) with ∣δ∣≤u\abs{\delta} \le u. With v=x−αe1\vb{v} = \vb{x} - \alpha\vb{e}_1, destination α=+σ\alpha = +\sigma gives v^1\hat v_1 relative error of order 2cu/θ22cu/\theta^2 for small θ\theta, while destination α=−σ\alpha = -\sigma bounds it by (c+1)u+O(u2)(c + 1)u + \bigO(u^2).
0
Only v1v_1 involves arithmetic: vi=xiv_i = x_i for i≥2i \ge 2 are copied exactly. Write x1=σcos⁡θx_1 = \sigma\cos\theta.

Step 1 of 4. What is exact v1v_1 with α=+σ\alpha = +\sigma?

CodeHouseholder without forming Q
Implement householder_qr(A) returning (V, R): V is an m×nm\times n matrix whose column kk is the unit vector vk\vb{v}_k of reflector Hk=I−2vkvk⊤\mat{H}_k = \mat{I} - 2\vb{v}_k\vb{v}_k\T (with zeros before entry kk), and R is the n×nn\times n upper triangular factor. Also implement apply_qt(V, b) returning Q⊤b=Hn⋯H1b\mat{Q}\T\vb{b} = \mat{H}_n\cdots\mat{H}_1\vb{b} (a vector of length mm) without forming Q\mat{Q}. Handle the sign and x1=0x_1 = 0 carefully. Assume m≥nm \ge n.
import numpy as np

def householder_qr(A):
  A = np.array(A, dtype=float)
  m, n = A.shape
  V = np.zeros((m, n))
  # tu código: para cada k, el reflector de A[k:, k] y su aplicación a A[k:, k:]
  R = np.triu(A[:n])
  return V, R

def apply_qt(V, b):
  b = np.array(b, dtype=float)
  # tu código
  return b
Shift+Enter to run
CodeAdd a row to QR
Implement anadir_fila(R, a): given R\mat{R} (n×nn\times n, upper triangular) from the QR of A\mat{A} and a new row a∈Rn\vb{a} \in \R^n, return R\mat{R} for matrix [Aa⊤]\begin{bmatrix} \mat{A} \\ \vb{a}\T \end{bmatrix} using nn Givens rotations without A\mat{A} or Q\mat{Q}. The returned R\mat{R} must have nonnegative diagonal and work with entries of size 1020010^{200}.
import numpy as np

def anadir_fila(R, a):
  R = np.array(R, dtype=float)
  w = np.array(a, dtype=float)
  # tu código: para k = 0..n-1, una rotación entre la fila k de R y w que anule w[k]
  return R
Shift+Enter to run

Summary

Key idea
Orthogonal transformations do not amplify errors, so a factorization built from them (Householder, Givens) is backward stable regardless of κ. Gram–Schmidt constructs Q instead of applying it and loses orthogonality in proportion to κ (MGS) or κ² (CGS), while normal equations always solve a problem with κ².
  • Errors in a chain of orthogonal transformations add instead of multiplying; Householder QR is therefore columnwise backward stable and its Q^\hat{\mat{Q}} orthogonal to uu for any κ\kappa.
  • CGS loses orthogonality as uκ2u\kappa^2 because its R^\hat{\mat{R}} is essentially Cholesky of A⊤A\mat{A}\T\mat{A}; MGS as uκu\kappa, and its R^\hat{\mat{R}} is as good as Householder’s; CGS2 maintains uu if uκ≪1u\kappa \ll 1. For MGS least squares, factor [A b][\mat{A}\ \vb{b}].
  • Householder in practice: destination −sign⁡(x1)∥x∥e1-\operatorname{sign}(x_1)\norm{\vb{x}}\vb{e}_1 (or Parlett’s formula), reflectors normalized with v1=1v_1 = 1 stored below the diagonal, Q⊤b\mat{Q}\T\vb{b} in 4mn4mn flops without forming Q\mat{Q}, and 2mn2−2n3/32mn^2 - 2n^3/3 flops total.
  • With R~\tilde{\mat{R}} of [A b][\mat{A}\ \vb{b}], a new observation is incorporated using n+1n + 1 Givens rotations and about 3n23n^2 flops, updating the residual automatically; exponential forgetting gives rolling regressions. Row removal is more delicate.
  • The least-squares problem has condition number κ+κ2tan⁡θ/η\kappa + \kappa^2\tan\theta/\eta; QR and SVD achieve it, normal equations always pay κ2\kappa^2 and can lose information when forming A⊤A\mat{A}\T\mat{A}. Column scaling reduces κ\kappa for free.
  • With deficient rank, pivoted QR cheaply estimates rank (but can fail, as with Kahan’s matrix) and truncated SVD yields the minimum-norm solution. Data noise determines tolerance, not machine epsilon.