Module contents
Lesson 9 of 25Core 100 min

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 q1,…,qn\vb{q}_1, \dots, \vb{q}_n turns coordinate problems into dot products. Put it in the columns of a matrix Q\mat{Q} and three problems that generally require solving a linear system become trivial:

  • Coordinates. In an arbitrary basis, finding c\vb{c} with Bc=x\mat{B}\vb{c} = \vb{x} requires solving a system. In an orthonormal basis, ci=qi⊤xc_i = \vb{q}_i\T\vb{x}, i.e. c=Q⊤x\vb{c} = \mat{Q}\T\vb{x}: one multiplication.
  • Projections. The projection matrix onto col⁡(A)\col(\mat{A}) is A(A⊤A)−1A⊤\mat{A}(\mat{A}\T\mat{A})\inv\mat{A}\T. If columns are orthonormal, Q⊤Q=I\mat{Q}\T\mat{Q} = \mat{I} and the formula reduces to QQ⊤\mat{Q}\mat{Q}\T.
  • Least squares. The normal equations A⊤Ax=A⊤b\mat{A}\T\mat{A}\vb{x} = \mat{A}\T\vb{b} become x=Q⊤b\vb{x} = \mat{Q}\T\vb{b}.

A second reason is less visible and more important in practice: matrices with orthonormal columns amplify nothing. Multiplication by Q\mat{Q} 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 2×22\times 2 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 SO(3)SO(3): rotations of R3\R^3.
  • Recent optimizers. Muon orthogonalizes each weight matrix update using a Newton–Schulz iteration.

This lesson solves the inverse problem: given any matrix A\mat{A}, construct an orthonormal basis of its column space while recording how the columns of A\mat{A} are written in that basis. The result is factorization A=QR\mat{A} = \mat{Q}\mat{R}. 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. [111−1]\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix} has perpendicular columns and satisfies A⊤A=2I\mat{A}\T\mat{A} = 2\mat{I}; divided by 2\sqrt{2} it is orthogonal.

For a square matrix, Q⊤Q=I\mat{Q}\T\mat{Q} = \mat{I} says Q⊤\mat{Q}\T is a left inverse; in finite dimensions this makes it the inverse, so QQ⊤=I\mat{Q}\mat{Q}\T = \mat{I} too and rows are orthonormal. Inverting an orthogonal matrix means transposing it, requiring no arithmetic operations.

The situation changes if Q∈Rm×n\mat{Q} \in \R^{m\times n} with m>nm > n has orthonormal columns. It still satisfies Q⊤Q=In\mat{Q}\T\mat{Q} = \mat{I}_n, but QQ⊤\mat{Q}\mat{Q}\T, of size m×mm\times m and rank nn, cannot be identity: it is the orthogonal projector onto col⁡(Q)\col(\mat{Q}). 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 ∥Qz∥2=∥z∥2\norm{\mat{Q}\vb{z}}^2 = \norm{\vb{z}}^2 for every z\vb{z}, and apply it to z=x+y\vb{z} = \vb{x} + \vb{y}:

∥Qx∥2+2(Qx)⊤(Qy)+∥Qy∥2=∥x∥2+2x⊤y+∥y∥2.\norm{\mat{Q}\vb{x}}^2 + 2(\mat{Q}\vb{x})\T(\mat{Q}\vb{y}) + \norm{\mat{Q}\vb{y}}^2 = \norm{\vb{x}}^2 + 2\vb{x}\T\vb{y} + \norm{\vb{y}}^2 .

The squares cancel in pairs, giving x⊤(Q⊤Q)y=x⊤y\vb{x}\T(\mat{Q}\T\mat{Q})\vb{y} = \vb{x}\T\vb{y} for all x,y\vb{x}, \vb{y}. With x=ei\vb{x} = \vb{e}_i and y=ej\vb{y} = \vb{e}_j we obtain (Q⊤Q)ij=δij(\mat{Q}\T\mat{Q})_{ij} = \delta_{ij}.

∎
ProofWhat an orthogonal matrix preserves
Prove: If Q⊤Q=I\mat{Q}\T\mat{Q} = \mat{I}, then Q\mat{Q} preserves dot products, norms and angles, and if square, det⁡Q=±1\det\mat{Q} = \pm 1.
0
Let Q∈Rm×n\mat{Q} \in \R^{m\times n} with Q⊤Q=In\mat{Q}\T\mat{Q} = \mat{I}_n and x,y∈Rn\vb{x}, \vb{y} \in \R^n.

Step 1 of 4. How do you start with the dot product?

Orthogonal matrices n×nn\times n form a group: if Q1,Q2∈O(n)\mat{Q}_1, \mat{Q}_2 \in O(n), then (Q1Q2)⊤(Q1Q2)=Q2⊤Q1⊤Q1Q2=I(\mat{Q}_1\mat{Q}_2)\T(\mat{Q}_1\mat{Q}_2) = \mat{Q}_2\T\mat{Q}_1\T\mat{Q}_1\mat{Q}_2 = \mat{I}, and Q−1=Q⊤\mat{Q}\inv = \mat{Q}\T is orthogonal too. The determinant splits the group in two: those with det⁡=+1\det = +1, forming the subgroup SO(n)SO(n) of rotations, and those with det⁡=−1\det = -1, reversing orientation like a mirror.

The plane: rotations and reflections

In R2\R^2 we can write the whole of O(2)O(2). The first column of Q\mat{Q} is a unit vector, so it is (cos⁡θ,sin⁡θ)(\cos\theta, \sin\theta) for some θ\theta. The second is unit and perpendicular to the first: there are only two candidates, (−sin⁡θ,cos⁡θ)(-\sin\theta, \cos\theta), rotated 90°90° counterclockwise, and (sin⁡θ,−cos⁡θ)(\sin\theta, -\cos\theta), rotated 90°90° clockwise. This gives exactly two families:

Rθ=[cos⁡θ−sin⁡θsin⁡θcos⁡θ],Fθ=[cos⁡θsin⁡θsin⁡θ−cos⁡θ],\begin{gathered} \mat{R}_\theta = \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}, \\[6pt] \mat{F}_\theta = \begin{bmatrix} \cos\theta & \sin\theta \\ \sin\theta & -\cos\theta \end{bmatrix}, \end{gathered}

with det⁡Rθ=1\det\mat{R}_\theta = 1 and det⁡Fθ=−1\det\mat{F}_\theta = -1.

The first is rotation by angle θ\theta. Fθ\mat{F}_\theta is reflection across the line at angle θ/2\theta/2 to axis xx: it fixes vector (cos⁡θ2,sin⁡θ2)(\cos\frac{\theta}{2}, \sin\frac{\theta}{2}) and negates its perpendicular, as double-angle formulas confirm. Composing with the same trigonometric formulas,

FθFφ=Rθ−φ,RθFφ=Fθ+φ:\mat{F}_\theta\mat{F}_\varphi = \mat{R}_{\theta - \varphi}, \qquad \mat{R}_\theta\mat{F}_\varphi = \mat{F}_{\theta + \varphi}:

two mirrors make a rotation through twice their angle, and a rotation followed by a reflection is another reflection.

InteractiveRotate or reflect
  • original hand
  • transformed hand
  • Qe1\mat{Q}\vb{e}_1
  • Qe2\mat{Q}\vb{e}_2
  • mirror
Mode
Orthogonal matrix
100°
Q=[−0.170.980.980.17]\mat{Q} = \begin{bmatrix} -0.17 & 0.98 \\ 0.98 & 0.17 \end{bmatrix}
Typereflection (mirror at 50°)
det⁡Q\det \mat{Q}−1.00
Q⊤Q=I\mat{Q}\T\mat{Q} = \mat{I}?yes
Orientationreversed
Qe2\mat{Q}\vb{e}_2 is 90°90° behind Qe1\mat{Q}\vb{e}_1: orientation reverses and the right hand becomes a left hand. No rotation of the plane restores its shape.
The silhouette is a right hand viewed from the back. Choose rotation or reflection and move θ\theta: columns Qe1\mat{Q}\vb{e}_1 and Qe2\mat{Q}\vb{e}_2 remain unit and perpendicular, but in a rotation Qe2\mat{Q}\vb{e}_2 is 90°90° ahead of Qe1\mat{Q}\vb{e}_1, and in a reflection 90°90° behind (shown by the small arc). Press ‘Animate from I’ with reflection: the straight path from identity passes through det⁡=0\det = 0 and the hand is flattened. In ‘Two reflections’, verify the resulting rotation is twice the angle between mirrors.

What you saw has a useful topological interpretation. The determinant is continuous in its entries and on O(n)O(n) takes only values ±1\pm 1, so no continuous path of orthogonal matrices takes a rotation to a reflection: O(n)O(n) has two separate pieces. The animation must leave O(2)O(2) 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 R3\R^3 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 O(n)O(n) is a product of at most nn reflections. You will encounter it almost for free with Householder.

For computation, length preservation matters. If a vector arrives with error δx\delta\vb{x}, multiplying by Q\mat{Q} produces error Q δx\mat{Q}\,\delta\vb{x} of the same length: neither amplified nor reduced. The condition number, maximum relative error amplification studied in lesson 16, is κ(Q)=1\kappa(\mat{Q}) = 1, the minimum possible. Multiplying another matrix by Q\mat{Q} does not change its conditioning: κ(QA)=κ(A)\kappa(\mat{Q}\mat{A}) = \kappa(\mat{A}). 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 O(n)O(n), the unique distribution invariant under multiplication by a fixed orthogonal matrix. The standard recipe previews this lesson’s protagonist: take Q\mat{Q} 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, r11r_{11} has sign opposite a11a_{11}, so q11=a11/r11q_{11} = a_{11}/r_{11} is always negative. Correct this by multiplying columns of Q\mat{Q} by signs of the diagonal of R\mat{R} (Mezzadri, 2007), as scipy.stats.ortho_group and torch.nn.init.orthogonal_ do.

[ ]Random orthogonal matrix, with and without sign correctionBrowser
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 a1,…,an∈Rm\vb{a}_1, \dots, \vb{a}_n \in \R^m be linearly independent. We want orthonormal vectors q1,…,qn\vb{q}_1, \dots, \vb{q}_n spanning the same space, in the same order: the first kk of q\vb{q} should span the same as the first kk of a\vb{a}, for each kk. This extra requirement makes the result a useful factorization.

The idea uses orthogonal projection. If q\vb{q} is unit, the shadow of a\vb{a} on the line of q\vb{q} is (q⊤a) q(\vb{q}\T\vb{a})\,\vb{q}, and a−(q⊤a) q\vb{a} - (\vb{q}\T\vb{a})\,\vb{q} is perpendicular to q\vb{q}. Gram–Schmidt repeats this: subtract each new vector’s shadow on everything already built, then normalize what remains.

Proof

Induct on kk. For k=1k = 1, a1≠0\vb{a}_1 \ne \vb{0} because it belongs to an independent family, and q1=a1/∥a1∥\vb{q}_1 = \vb{a}_1/\norm{\vb{a}_1} spans the same line.

Suppose the result holds through k−1k - 1. If vk=0\vb{v}_k = \vb{0}, then ak=∑j<krjkqj∈span⁡{q1,…,qk−1}=span⁡{a1,…,ak−1}\vb{a}_k = \sum_{j<k} r_{jk}\vb{q}_j \in \spn\{\vb{q}_1, \dots, \vb{q}_{k-1}\} = \spn\{\vb{a}_1, \dots, \vb{a}_{k-1}\}, contradicting independence; thus rkk>0r_{kk} > 0. For i<ki < k, using orthonormality of the previous qj\vb{q}_j,

qi⊤vk=qi⊤ak−∑j<krjk qi⊤qj=rik−rik=0,\vb{q}_i\T\vb{v}_k = \vb{q}_i\T\vb{a}_k - \sum_{j<k} r_{jk}\,\vb{q}_i\T\vb{q}_j = r_{ik} - r_{ik} = 0,

so qk\vb{q}_k is unit and perpendicular to the earlier vectors. Finally, qk\vb{q}_k is a combination of ak\vb{a}_k and q1,…,qk−1\vb{q}_1, \dots, \vb{q}_{k-1}, while ak=∑j≤krjkqj\vb{a}_k = \sum_{j\le k} r_{jk}\vb{q}_j: 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 1,t,t2,t31, t, t^2, t^3 with ⟨f,g⟩=∫−11f(t)g(t) ⁣dt\inner{f}{g} = \int_{-1}^{1} f(t)g(t)\dd t, the shadow of t2t^2 on 11 is ⟨t2,1⟩⟨1,1⟩=2/32=13\frac{\inner{t^2}{1}}{\inner{1}{1}} = \frac{2/3}{2} = \frac{1}{3} and on tt is zero by symmetry, so the second remainder is t2−13t^2 - \frac{1}{3}; the next is t3−35tt^3 - \frac{3}{5}t. 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.

InteractiveGram–Schmidt step by step
Press play: each step subtracts from ak\vb{a}_k its shadow on what is already built (gray arrow and dashed drop) and normalizes the remainder, while R\mat{R} fills column by column. Drag tips to bring vectors closer and watch ‘what survives’, rkk/∥ak∥r_{kk}/\norm{\vb{a}_k}. Then choose ‘Nearly parallel’, switch to ‘3 digits’ and go to the last step: classical computed q3\vb{q}_3 differs from exact by about 45°45°; modified differs by only 2°2°.

What matters in the observation:

  • Remainders may be tiny. When ak\vb{a}_k is nearly in the previous vectors’ plane, vk\vb{v}_k is the difference of nearly equal vectors ak\vb{a}_k and its shadow. If 1 %1\,\% of ak\vb{a}_k survives, relative data error uu becomes relative error around 100 u100\,u in vk\vb{v}_k. This is catastrophic cancellation, and no care in normalization fixes it.
  • Error has a direction. What leaks into vk\vb{v}_k are remnants of components meant to be removed, i.e. along q1,…,qk−1\vb{q}_1, \dots, \vb{q}_{k-1}. The symptom is not qk\vb{q}_k with wrong length (it is normalized at the end), but qk\vb{q}_k no longer perpendicular to previous vectors.
  • Double precision hides this unless vectors are extraordinarily close. Three-digit arithmetic, with unit roundoff u=5⋅10−3u = 5\cdot 10^{-3} instead of u=2−53≈1.1⋅10−16u = 2^{-53} \approx 1.1\cdot 10^{-16}, magnifies the same phenomena to a visible scale.

QR factorization

Solving for ak\vb{a}_k from the definition of vk\vb{v}_k gives

ak=r1kq1+r2kq2+⋯+rkkqk,\vb{a}_k = r_{1k}\vb{q}_1 + r_{2k}\vb{q}_2 + \dots + r_{kk}\vb{q}_k ,

which is column kk of a matrix product: column kk of A\mat{A} is Q\mat{Q} times a vector whose entries below kk are zero.

In the previous example,

[3−11002473]=[0.6−0.800010.80.60][553051002].\begin{bmatrix} 3 & -1 & 1 \\ 0 & 0 & 2 \\ 4 & 7 & 3 \end{bmatrix} = \begin{bmatrix} 0.6 & -0.8 & 0 \\ 0 & 0 & 1 \\ 0.8 & 0.6 & 0 \end{bmatrix}\begin{bmatrix} 5 & 5 & 3 \\ 0 & 5 & 1 \\ 0 & 0 & 2 \end{bmatrix}.
Proof

Existence follows from the previous theorem. For uniqueness, let A=QR\mat{A} = \mat{Q}\mat{R} be any reduced QR with positive diagonal. Since R\mat{R} is upper triangular with nonzero diagonal, a1,…,ak\vb{a}_1, \dots, \vb{a}_k are combinations of q1,…,qk\vb{q}_1, \dots, \vb{q}_k and vice versa (the inverse of an upper triangular matrix is also upper triangular), so span⁡{q1,…,qk}=span⁡{a1,…,ak}=:Sk\spn\{\vb{q}_1, \dots, \vb{q}_k\} = \spn\{\vb{a}_1, \dots, \vb{a}_k\} =: S_k for each kk. Then qk\vb{q}_k is a unit vector in SkS_k perpendicular to Sk−1S_{k-1}, a subspace of dimension k−1k - 1 inside SkS_k, which has dimension kk. Only two such vectors exist, opposite one another, and rkk=qk⊤ak>0r_{kk} = \vb{q}_k\T\vb{a}_k > 0 selects one. Once Q\mat{Q} is fixed, R=Q⊤A\mat{R} = \mat{Q}\T\mat{A} is determined.

∎

Without the sign condition, QR is unique up to a matrix D=diag⁡(±1)\mat{D} = \diag(\pm 1): A=(QD)(DR)\mat{A} = (\mat{Q}\mat{D})(\mat{D}\mat{R}). 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: Q1\mat{Q}_1 is an orthonormal basis of col⁡(A)\col(\mat{A}) and Q2\mat{Q}_2, perpendicular to it, is an orthonormal basis of its complement null⁡(A⊤)\nullsp(\mat{A}\T).

The diagonal of R\mat{R} also tells a story. If A\mat{A} is square, det⁡A=det⁡Q det⁡R=± r11r22⋯rnn\det\mat{A} = \det\mat{Q}\,\det\mat{R} = \pm\, r_{11}r_{22}\cdots r_{nn}, and since rkkr_{kk} is the distance of ak\vb{a}_k from previous vectors, ∣det⁡A∣=∏krkk\abs{\det\mat{A}} = \prod_k r_{kk} is the “base times height” formula for determinant as volume: the parallelogram area of a1,a2\vb{a}_1, \vb{a}_2 is r11r22r_{11}r_{22}, and each new column multiplies by its height above the previous ones. In the example ∣det⁡A∣=5⋅5⋅2=50\abs{\det\mat{A}} = 5\cdot 5\cdot 2 = 50; the negative sign comes from det⁡Q=−1\det\mat{Q} = -1.

NumericAn entry of R
Let A\mat{A} be the 3×23\times 2 matrix with columns a1=(1,1,0)\vb{a}_1 = (1, 1, 0) and a2=(1,0,1)\vb{a}_2 = (1, 0, 1). Calculate r22r_{22} in its QR factorization with positive diagonal.

Gram–Schmidt performs AR−1=Q\mat{A}\mat{R}\inv = \mat{Q}: it right-multiplies A\mat{A} by triangular matrices until orthonormal. Trefethen and Bau call this triangular orthogonalization. It costs about 2mn22mn^2 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 ak\vb{a}_k from the original vector, rjk=qj⊤akr_{jk} = \vb{q}_j\T\vb{a}_k, and subtracts them together. Modified Gram–Schmidt (MGS) subtracts each shadow immediately and projects the partially cleaned vector:

rjk=qj⊤vk(j),vk(j+1)=vk(j)−rjkqj,j=1,…,k−1,r_{jk} = \vb{q}_j\T\vb{v}_k^{(j)}, \qquad \vb{v}_k^{(j+1)} = \vb{v}_k^{(j)} - r_{jk}\vb{q}_j, \qquad j = 1, \dots, k - 1,

starting at vk(1)=ak\vb{v}_k^{(1)} = \vb{a}_k and ending at vk=vk(k)\vb{v}_k = \vb{v}_k^{(k)}.

In exact arithmetic these are the same algorithm: qj⊤vk(j)=qj⊤ak−∑i<jrik qj⊤qi=qj⊤ak\vb{q}_j\T\vb{v}_k^{(j)} = \vb{q}_j\T\vb{a}_k - \sum_{i<j} r_{ik}\,\vb{q}_j\T\vb{q}_i = \vb{q}_j\T\vb{a}_k, because qj⊤qi=0\vb{q}_j\T\vb{q}_i = 0. Written with projectors, CGS applies I−Qk−1Qk−1⊤\mat{I} - \mat{Q}_{k-1}\mat{Q}_{k-1}\T at once, with Qk−1=[q1⋯qk−1]\mat{Q}_{k-1} = [\vb{q}_1 \cdots \vb{q}_{k-1}], while MGS applies elementary projectors one after another:

CGS:vk=(I−∑j<kqjqj⊤)ak,MGS:vk=(I−qk−1qk−1⊤)⋯(I−q1q1⊤) ak.\begin{aligned} \text{CGS:}\quad \vb{v}_k &= \Big(\mat{I} - \sum_{j<k} \vb{q}_j\vb{q}_j\T\Big)\vb{a}_k, \\ \text{MGS:}\quad \vb{v}_k &= (\mat{I} - \vb{q}_{k-1}\vb{q}_{k-1}\T)\cdots(\mat{I} - \vb{q}_1\vb{q}_1\T)\,\vb{a}_k . \end{aligned}

Expanding the product produces cross terms with factors qi⊤qj\vb{q}_i\T\vb{q}_j, zero if the q\vb{q} 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 q\vb{q}.

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 κ(A)\kappa(\mat{A}), the ratio of maximum and minimum stretch applied by A\mat{A} to unit vectors, and unit roundoff uu (machine precision). Known results are:

  • MGS: ∥I−Q⊤Q∥≲c u κ(A)\norm{\mat{I} - \mat{Q}\T\mat{Q}} \lesssim c\,u\,\kappa(\mat{A}) (Björck, 1967).
  • CGS: ∥I−Q⊤Q∥≲c u κ(A)2\norm{\mat{I} - \mat{Q}\T\mat{Q}} \lesssim c\,u\,\kappa(\mat{A})^2, provided u κ(A)2u\,\kappa(\mat{A})^2 is small; otherwise there is no guarantee (Giraud, Langou, Rozložník and van den Eshof, 2005).
  • Householder (next section): ∥I−Q⊤Q∥≲c u\norm{\mat{I} - \mat{Q}\T\mat{Q}} \lesssim c\,u, independent of κ(A)\kappa(\mat{A}).

Where do these powers of κ\kappa come from? Rigorous analysis is delicate, but the CGS mechanism appears in one line. In exact arithmetic, A⊤A=R⊤Q⊤QR=R⊤R\mat{A}\T\mat{A} = \mat{R}\T\mat{Q}\T\mat{Q}\mat{R} = \mat{R}\T\mat{R}: the Gram–Schmidt R\mat{R} is a Cholesky factor of A⊤A\mat{A}\T\mat{A}, and CGS, computing each column of R\mat{R} from dot products of original columns, behaves as if factoring A⊤A\mat{A}\T\mat{A}. Suppose computed R\mat{R} satisfies R⊤R=A⊤A+E\mat{R}\T\mat{R} = \mat{A}\T\mat{A} + \mat{E} with ∥E∥≈u∥A∥2\norm{\mat{E}} \approx u\norm{\mat{A}}^2, and Q=AR−1\mat{Q} = \mat{A}\mat{R}\inv. Then

Q⊤Q−I=R−⊤(A⊤A−R⊤R)R−1=−R−⊤E R−1,∥Q⊤Q−I∥≲u ∥A∥2 ∥R−1∥2=u κ(A)2,\begin{aligned} \mat{Q}\T\mat{Q} - \mat{I} &= \mat{R}^{-\top}\big(\mat{A}\T\mat{A} - \mat{R}\T\mat{R}\big)\mat{R}\inv = -\mat{R}^{-\top}\mat{E}\,\mat{R}\inv, \\ \norm{\mat{Q}\T\mat{Q} - \mat{I}} &\lesssim u\,\norm{\mat{A}}^2\,\norm{\mat{R}\inv}^2 = u\,\kappa(\mat{A})^2, \end{aligned}

where the last equality uses ∥Ax∥=∥QRx∥=∥Rx∥\norm{\mat{A}\vb{x}} = \norm{\mat{Q}\mat{R}\vb{x}} = \norm{\mat{R}\vb{x}}: R\mat{R} stretches exactly as A\mat{A}. CGS pays the same price as normal equations for the same reason: implicitly it works with A⊤A\mat{A}\T\mat{A}. MGS errors instead correspond to an orthogonal transformation applied to a slightly perturbed A\mat{A}, introducing only one factor ∥A∥ ∥R−1∥=κ\norm{\mat{A}}\,\norm{\mat{R}\inv} = \kappa. Householder does not depend on R−1\mat{R}\inv at all.

Constants cc depend on mm and nn polynomially and modestly. Do not just believe the bounds: measure them.

InteractiveOrthogonality-loss race
Each point is a 40×1240\times 12 matrix constructed with prescribed condition number κ\kappa, factored in actual double precision (the same arithmetic as NumPy). Change κ\kappa: CGS rises with slope 2 (parallel to uκ2u\kappa^2) until it loses all orthogonality around κ≈108\kappa \approx 10^8, MGS rises with slope 1, and Householder stays at uu. Heat maps show where loss occurs: CGS between last columns; MGS between first and last. Enable CGS2 to see what repeated orthogonalization achieves.

Three observations from the experiment:

  • Slopes match theory. Each decade of κ\kappa costs CGS two digits of orthogonality and MGS one. At κ=108\kappa = 10^8, typical of moderate-degree polynomial regression, CGS no longer returns an orthonormal basis.
  • MGS is not a complete remedy. With κ=1012\kappa = 10^{12} its columns have dot products between 10−510^{-5} and 10−410^{-4} (of order uκu\kappa): treating that Q\mat{Q} as orthogonal (e.g. to compute Q⊤b\mat{Q}\T\vb{b}) inherits the error.
  • Reorthogonalization works. A second CGS projection (CGS2) restores orthogonality to uu as long as A\mat{A} 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 kk dependent dot products. Large-scale Krylov methods (Arnoldi, GMRES) therefore often use CGS2.

Householder reflections: triangularizing with mirrors

Gram–Schmidt builds Q\mat{Q} column by column and loses orthogonality along the way. The alternative reverses the approach: apply to A\mat{A} a sequence of orthogonal transformations Q1,Q2,…\mat{Q}_1, \mat{Q}_2, \dots progressively making it triangular,

Qn⋯Q2Q1A=R.\mat{Q}_n\cdots\mat{Q}_2\mat{Q}_1\mat{A} = \mat{R} .

This is orthogonal triangularization. Each Qk\mat{Q}_k is orthogonal by construction, independent of previous calculations, and a product of orthogonal matrices is orthogonal, so Q=Q1⊤⋯Qn⊤\mat{Q} = \mat{Q}_1\T\cdots\mat{Q}_n\T is orthogonal regardless of κ(A)\kappa(\mat{A}). We need an orthogonal transformation that zeros all entries below a column’s diagonal. A suitably oriented mirror does this.

H\mat{H} is symmetric, orthogonal and involutive (H2=I\mat{H}^2 = \mat{I}: reflecting twice returns each point). Check it.

ProofProperties of the mirror
Prove: H=I−2vv⊤/(v⊤v)\mat{H} = \mat{I} - 2\vb{v}\vb{v}\T/(\vb{v}\T\vb{v}), with v≠0\vb{v} \ne \vb{0}, is symmetric, involutive and orthogonal, and reflects across hyperplane v⊥\vb{v}^\perp.
0
Let u=v/∥v∥\vb{u} = \vb{v}/\norm{\vb{v}}, so H=I−2uu⊤\mat{H} = \mat{I} - 2\vb{u}\vb{u}\T and u⊤u=1\vb{u}\T\vb{u} = 1.

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 ∥x∥=∥y∥\norm{\vb{x}} = \norm{\vb{y}} and x≠y\vb{x} \ne \vb{y}, take v=x−y\vb{v} = \vb{x} - \vb{y}. Then v⊤v=2∥x∥2−2 y⊤x=2 v⊤x\vb{v}\T\vb{v} = 2\norm{\vb{x}}^2 - 2\,\vb{y}\T\vb{x} = 2\,\vb{v}\T\vb{x} and

Hx=x−2v v⊤xv⊤v=x−v=y.\mat{H}\vb{x} = \vb{x} - 2\vb{v}\,\frac{\vb{v}\T\vb{x}}{\vb{v}\T\vb{v}} = \vb{x} - \vb{v} = \vb{y}.

The mirror is the perpendicular-bisector hyperplane of the segment joining x\vb{x} to y\vb{y}. To zero all of x\vb{x} except its first entry, two equal-length destinations are possible, y=±∥x∥e1\vb{y} = \pm\norm{\vb{x}}\vb{e}_1, and choosing badly is a classic mistake.

InteractiveThe Householder mirror
Drag x\vb{x}: the reflector uses v=x−destination\vb{v} = \vb{x} - \text{destination} (the arrow from destination to x\vb{x}) and the mirror is perpendicular to v\vb{v}. With ‘Stable’, the destination lies opposite x\vb{x} and v\vb{v} is long. Choose ‘Always +∥x∥e1+\norm{\vb{x}}\vb{e}_1’, move x\vb{x} close to the axis with the angle slider and reduce to 2 or 3 digits: v\vb{v} becomes tiny, its direction is determined by rounding, and Hx\mat{H}\vb{x} no longer lands on the axis. The plot measures error for all angles: the naive destination follows line u/θu/\theta and can lose half the digits.

The analysis takes one line. With destination +∥x∥e1+\norm{\vb{x}}\vb{e}_1, the first component of v\vb{v} is v1=x1−∥x∥v_1 = x_1 - \norm{\vb{x}}. If x\vb{x} makes a small angle θ\theta with e1\vb{e}_1, then x1≈∥x∥(1−θ2/2)x_1 \approx \norm{\vb{x}}(1 - \theta^2/2) and v1≈−∥x∥ θ2/2v_1 \approx -\norm{\vb{x}}\,\theta^2/2: subtracting numbers agreeing in their first digits leaves relative error of order u/θ2u/\theta^2, and computed Hx\mat{H}\vb{x} deviates from the axis by a fraction of order u/θu/\theta. Error grows until θ≈u\theta \approx \sqrt{u}; for smaller angles the wrong mirror barely moves x\vb{x} and error falls again, as θ\theta. Worst case, u≈10−8\sqrt{u} \approx 10^{-8} in double precision, loses half the digits. Choosing destination −sgn⁡(x1)∥x∥e1-\sgn(x_1)\norm{\vb{x}}\vb{e}_1 gives

v=x+sgn⁡(x1)∥x∥ e1,v1=x1+sgn⁡(x1)∥x∥,\vb{v} = \vb{x} + \sgn(x_1)\norm{\vb{x}}\,\vb{e}_1, \qquad v_1 = x_1 + \sgn(x_1)\norm{\vb{x}},

a sum of two same-sign numbers that cannot cancel. Here choose sgn⁡(0)=1\sgn(0) = 1: NumPy’s np.sign returns 00 at 00, and then v=x\vb{v} = \vb{x} and the mirror maps x\vb{x} to −x-\vb{x} without zeroing anything. If the positive destination is required, formula v1=−(x22+⋯+xm2)/(x1+∥x∥)v_1 = -(x_2^2 + \dots + x_m^2)/(x_1 + \norm{\vb{x}}), algebraically identical for x1>0x_1 > 0, avoids subtraction.

Notice the subtlety: with the wrong sign H\mat{H} remains perfectly orthogonal, because any v\vb{v} 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 R\mat{R}.

Householder QR

At step kk earlier columns already have zeros below the diagonal; for column kk consider only segment x=Ak:m, k\vb{x} = \mat{A}_{k:m,\,k} from the diagonal down. Build reflector Hk\mat{H}_k of size (m−k+1)(m - k + 1) mapping x\vb{x} to a multiple of e1\vb{e}_1 and apply it to rows k,…,mk, \dots, m of columns k,…,nk, \dots, n. The full transformation is block diagonal Qk=diag⁡(Ik−1,Hk)\mat{Q}_k = \diag(\mat{I}_{k-1}, \mat{H}_k), leaving completed rows untouched. For an A\mat{A} of 4×34\times 3:

[××××××××××××]→ Q1 [×××0××0××0××]→ Q2 [×××0××00×00×]→ Q3 [×××0××00×000]\begin{bmatrix} \times & \times & \times \\ \times & \times & \times \\ \times & \times & \times \\ \times & \times & \times \end{bmatrix} \xrightarrow{\ \mat{Q}_1\ } \begin{bmatrix} \times & \times & \times \\ 0 & \times & \times \\ 0 & \times & \times \\ 0 & \times & \times \end{bmatrix} \xrightarrow{\ \mat{Q}_2\ } \begin{bmatrix} \times & \times & \times \\ 0 & \times & \times \\ 0 & 0 & \times \\ 0 & 0 & \times \end{bmatrix} \xrightarrow{\ \mat{Q}_3\ } \begin{bmatrix} \times & \times & \times \\ 0 & \times & \times \\ 0 & 0 & \times \\ 0 & 0 & 0 \end{bmatrix}

The result is R\mat{R} of full QR: triangle R1\mat{R}_1 above a row of zeros.

Three details turn this into the production algorithm:

  • Q\mat{Q} is not formed. Store only the nn vectors vk\vb{v}_k, which fit in the lower triangle of A\mat{A} as the algorithm zeros it. LAPACK normalizes v1=1v_1 = 1 and separately stores scalar τk\tau_k with Hk=I−τkvkvk⊤\mat{H}_k = \mat{I} - \tau_k\vb{v}_k\vb{v}_k\T; this is what np.linalg.qr(A, mode="raw") returns.
  • Applying Q⊤\mat{Q}\T is cheap. Compute Q⊤b=Hn⋯H1b\mat{Q}\T\vb{b} = \mat{H}_n\cdots\mat{H}_1\vb{b} reflector by reflector, with a dot product and an update per step: about 4mn4mn flops, never building an m×mm\times m matrix or m×nm\times n. Explicitly forming Q\mat{Q} costs order mn2mn^2 extra flops and is needed only if its columns are required.
  • Total cost of obtaining R\mat{R} is about 2mn2−23n32mn^2 - \tfrac{2}{3}n^3 flops: like Gram–Schmidt if m≫nm \gg n, and 43n3\tfrac{4}{3}n^3 for a square matrix, twice LU factorization.

The decisive property: Householder QR is backward stable. Computed factors are the exact QR of a matrix A+δA\mat{A} + \delta\mat{A} with ∥δA∥/∥A∥=O(u)\norm{\delta\mat{A}}/\norm{\mat{A}} = \bigO(u), and Q\mat{Q} defined by computed reflectors is orthogonal to uu (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 −sgn⁡(x1)∥x∥e1-\sgn(x_1)\norm{\vb{x}}\vb{e}_1, Householder’s R\mat{R} 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 Q\mat{Q} and rows of R\mat{R}.

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 bb in row kk using entry aa in row ii of the same column, choose θ\theta so vector (a,b)(a, b) rotates to the axis:

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

Calculate rr with np.hypot(a, b): the naive formula overflows if aa or bb exceeds 1015410^{154}, because their squares no longer fit in float64. θ\theta is unnecessary: cc and ss suffice.

InteractiveZeroing with Givens
13.001.002.00
22.001.00
31.00
4
5
Dashed: entries to zero. Magenta outline: last zeroed; amber: fill-in.
Rotation in the plane of the two rows
  • (a,b)(a, b) before
  • (r,0)(r, 0) after
Click a shaded entry to see its rotation here.
Pivot row to zero (i,j)(i, j)
[cs−sc]\begin{bmatrix} c & s \\ -s & c \end{bmatrix}
no rotations yet
Rotations applied0
Nonzero below diagonal9
∥A∥F\norm{\mat{A}}_F (invariant)7.3485
Click a shaded entry below the diagonal to zero it by rotating its row with the pivot row.
Click a shaded entry below the diagonal: rotating its row with the pivot row zeros it, and the small panel shows the plane of those rows, where (a,b)(a, b) rotates to (r,0)(r, 0). With pivot ‘row i−1i - 1’, zero entry (2,1)(2, 1) then (3,1)(3, 1): the second rotation fills the first again. Standard bottom-up, column-by-column order never fills it. Try ‘Hessenberg’ and ‘R plus a new row’: with the right structure few rotations suffice.

A dense matrix m×nm\times n needs one rotation per entry below the diagonal, and Givens QR costs about 3n2(m−n/3)3n^2(m - n/3) 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): n−1n - 1 rotations and O(n2)\bigO(n^2) flops instead of O(n3)\bigO(n^3). This is the central step of the QR eigenvalue algorithm.
  • Updating a factorization. If you have R\mat{R} for least squares and a new observation arrives, adding row a⊤\vb{a}\T below R\mat{R} gives a matrix triangularized with nn rotations in O(n2)\bigO(n^2), 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 A∈Rm×n\mat{A} \in \R^{m\times n} have rank nn and A=Q1R1\mat{A} = \mat{Q}_1\mat{R}_1 be its reduced QR, completed to Q=[Q1 Q2]∈O(m)\mat{Q} = [\mat{Q}_1\ \mat{Q}_2] \in O(m). Since Q⊤\mat{Q}\T preserves norms, minimizing ∥Ax−b∥\norm{\mat{A}\vb{x} - \vb{b}} can be rewritten in the basis of Q\mat{Q}:

∥Ax−b∥2=∥Q⊤(Ax−b)∥2\norm{\mat{A}\vb{x} - \vb{b}}^2 = \norm{\mat{Q}\T(\mat{A}\vb{x} - \vb{b})}^2
Q\mat{Q} is orthogonal: multiplication by Q⊤\mat{Q}\T preserves norm.
1/4

In practice compute c=Q1⊤b\vb{c} = \mat{Q}_1\T\vb{b} by applying reflectors (or MGS on the augmented matrix, as you will see), and solve R1x^=c\mat{R}_1\hat{\vb{x}} = \vb{c} by back substitution. The same follows from normal equations: A⊤A=R1⊤Q1⊤Q1R1=R1⊤R1\mat{A}\T\mat{A} = \mat{R}_1\T\mat{Q}_1\T\mat{Q}_1\mat{R}_1 = \mat{R}_1\T\mat{R}_1, so R1⊤R1x^=R1⊤Q1⊤b\mat{R}_1\T\mat{R}_1\hat{\vb{x}} = \mat{R}_1\T\mat{Q}_1\T\vb{b}, and canceling invertible R1⊤\mat{R}_1\T gives R1x^=Q1⊤b\mat{R}_1\hat{\vb{x}} = \mat{Q}_1\T\vb{b}. Incidentally, R1\mat{R}_1 is a Cholesky factor of A⊤A\mat{A}\T\mat{A}.

If both paths reach the same x^\hat{\vb{x}}, why not simply form A⊤A\mat{A}\T\mat{A}? Conditioning. If A\mat{A} stretches unit vectors between σmin⁡\sigma_{\min} and σmax⁡\sigma_{\max}, then A⊤A\mat{A}\T\mat{A} stretches them between σmin⁡2\sigma_{\min}^2 and σmax⁡2\sigma_{\max}^2 (immediate if A\mat{A} is diagonal; the general case follows from SVD), so

κ(A⊤A)=κ(A)2.\kappa(\mat{A}\T\mat{A}) = \kappa(\mat{A})^2 .

Normal equations solve a system whose matrix has squared conditioning, and relative error behaves as u κ(A)2u\,\kappa(\mat{A})^2. With κ(A)=108\kappa(\mat{A}) = 10^8, that is all digits gone. Householder QR works on A\mat{A} and is backward stable, so error is governed by the problem’s own sensitivity. A nuance: under perturbations of A\mat{A}, the least-squares condition number is of order κ+κ2tan⁡ϑ/η\kappa + \kappa^2\tan\vartheta/\eta, where ϑ\vartheta is the angle between b\vb{b} and its projection Ax^\mat{A}\hat{\vb{x}}, and 1≤η≤κ1 \le \eta \le \kappa (Trefethen and Bau, lecture 18). If the model fits well (small ϑ\vartheta), sensitivity is of order κ\kappa and QR gains a factor κ\kappa; with a large residual, term κ2\kappa^2 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 A\mat{A} 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 A⊤A\mat{A}\T\mat{A}.

NumericThe residual without solving
Using the same A\mat{A} as the previous exercise (columns (1,1,0)(1, 1, 0) and (1,0,1)(1, 0, 1)) and b=(3,0,0)\vb{b} = (3, 0, 0), calculate minimum residual min⁡x∥Ax−b∥\min_{\vb{x}}\norm{\mat{A}\vb{x} - \vb{b}} using full QR.

Implementation: three QR methods from scratch

The three factorizations fit on one screen. Notice Householder returns the reflectors rather than Q\mat{Q}, and the two functions operating on them.

[ ]Three QR methods from scratchBrowser
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 r11r_{11}: opposite a11a_{11}, as the stable choice predicts. np.copysign also handles the trap of sgn⁡(0)\sgn(0), because np.copysign(1.0, 0.0) equals 11.

The example’s Läuchli matrix separates the three immediately:

[ ]The Läuchli matrixBrowser
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 0.50.5 matches the hand calculation. MGS leaves q2⊤q3\vb{q}_2\T\vb{q}_3 at uu level, but q1⊤q3\vb{q}_1\T\vb{q}_3 is of order ε\eps: its u κu\,\kappa loss, with κ≈1.7⋅108\kappa \approx 1.7\cdot 10^8. Householder loses nothing.

Now repeat the interactive race with two classic ill-conditioned families: Hilbert matrices hij=1/(i+j−1)h_{ij} = 1/(i + j - 1) and Vandermonde matrices from polynomial fitting on [0,1][0, 1].

[ ]Orthogonality loss versus conditioningBrowser
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: κ\kappa governs, not the matrix’s origin. Hilbert 7×77\times 7, with κ≈5⋅108\kappa \approx 5\cdot 10^8, already strips CGS of orthogonality.

Finally, the decisive experiment following Trefethen and Bau (lecture 19): fit esin⁡4te^{\sin 4t} on [0,1][0, 1] with a degree-14 polynomial by least squares using m=100m = 100 points. Vector b\vb{b} is divided by 2006.7874530802062006.787453080206, the exact solution’s last coefficient, so the correct answer is x15=1x_{15} = 1 and error can be read directly.

[ ]Least squares: five ways to solve the same problemBrowser
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 κ(A)≈2⋅1010\kappa(\mat{A}) \approx 2\cdot 10^{10}:

  • Householder and np.linalg.lstsq achieve 6–8 correct digits (exact figures depend on BLAS and operation order): errors below u κ≈3⋅10−6u\,\kappa \approx 3\cdot 10^{-6}, the limit imposed by problem sensitivity.
  • Normal equations fail completely, even in sign: κ2≈5⋅1020\kappa^2 \approx 5\cdot 10^{20} greatly exceeds 1/u1/u. Their residual is only a few times optimal: a small residual does not guarantee an accurate solution in an ill-conditioned problem.
  • MGS with Q⊤b\mat{Q}\T\vb{b} loses several more digits than Householder because its Q\mat{Q} is not orthogonal. But MGS on augmented matrix [A b][\mat{A}\ \vb{b}] obtains Q⊤b\mat{Q}\T\vb{b} 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 n×nn\times n above A\mat{A} (Björck and Paige, 1992); the equivalence is lost if separately computed Q\mat{Q} is used.

The professional version: NumPy and SciPy

np.linalg.qr calls LAPACK routine geqrf, blocked Householder: it groups reflectors into transformation I−VTV⊤\mat{I} - \mat{V}\mat{T}\mat{V}\T for application via matrix products, which use cache much better. Its modes correspond to what you implemented:

[ ]np.linalg.qr and its modesBrowser
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 R\mat{R}, signs included, because both choose the stable destination. Mode "raw" returns the reflector matrix transposed (for Fortran-order compatibility) and τk\tau_k; scipy.linalg.qr_multiply applies Q\mat{Q} or Q⊤\mat{Q}\T without forming it.

QR has one final use shared with the more expensive SVD: revealing rank. If A\mat{A} has nearly dependent columns, some rkkr_{kk} is tiny, but without reordering it can appear anywhere. Column-pivoted QR, AP=QR\mat{A}\mat{P} = \mat{Q}\mat{R}, selects at each step the remaining column with largest norm after subtracting previous shadows, producing ∣r11∣≥∣r22∣≥⋯\abs{r_{11}} \ge \abs{r_{22}} \ge \cdots with redundant columns at the end.

[ ]Pivoted QR: numerical rank of a design matrixBrowser
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 rkkr_{kk} 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 rkkr_{kk}, around 10−810^{-8} and 5⋅10−115\cdot 10^{-11}, are well above threshold 2u⋅200⋅∣r11∣≈2⋅10−122u \cdot 200 \cdot \abs{r_{11}} \approx 2\cdot 10^{-12}. With tolerance appropriate to data precision, e.g. 10−610^{-6} 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 x1x_1 and x2x_2, 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

QuizOrthogonal or not?
Which matrices are orthogonal?

More than one answer may be correct.

NumericTwo mirrors
Reflect the plane across the line at 20°20° to the xx axis, then across the line at 65°65°. The composition is a rotation. How many degrees does it turn, taking counterclockwise as positive?
QuizA suspicious 0.5
You orthogonalize full-rank matrix A\mat{A} in double precision with classical Gram–Schmidt and obtain ∣q2⊤q3∣=0.5\abs{\vb{q}_2\T\vb{q}_3} = 0.5. Which statement is correct?
QuizWhich mirror?
You want to zero x2x_2 and x3x_3 in x=(5,10−9,0)\vb{x} = (5, 10^{-9}, 0) with a Householder reflector in double precision. What do you do?
NumericHow many rotations?
How many Givens rotations are generally required to bring a dense 5×35\times 3 matrix to upper triangular form, zeroing one entry per rotation?
QuizWhy QR?
Why is QR preferred over normal equations for least squares with ill-conditioned A\mat{A}?
NumericOne more observation
You have QR for least squares with one unknown: R=[3]\mat{R} = [3] and c=Q⊤b=(6)\vb{c} = \mat{Q}\T\vb{b} = (6), so x^=2\hat{x} = 2. A new observation arrives, 4x≈24x \approx 2. Update with a Givens rotation and give the new x^\hat{x}.
CodeHouseholder QR with positive diagonal
Implement householder_qr(A) without np.linalg.qr or scipy.linalg.qr. Return Q (m×nm\times n, orthonormal columns) and R (n×nn\times n, upper triangular with positive diagonal) satisfying A=QR\mat{A} = \mat{Q}\mat{R}, for full-rank A\mat{A} with m≥nm \ge n. Tests check reconstruction, shape of R, a column starting with 0, and ∥Q⊤Q−I∥<10−12\norm{\mat{Q}\T\mat{Q} - \mat{I}} < 10^{-12} 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 NotImplementedError
Shift+Enter to run
QuizQR of an orthogonal matrix
Apply Householder QR (without normalizing signs) to an orthogonal matrix Q0∈Rn×n\mat{Q}_0 \in \R^{n\times n}. What R\mat{R} results?
CodeOnline least squares with Givens
In a streaming system (prices, sensor readings), recomputing QR for every new observation costs O(mn2)\bigO(mn^2). Implement qr_add_row(R, c, a, beta): given R\mat{R} (n×nn\times n, upper triangular) and c=Q⊤b\vb{c} = \mat{Q}\T\vb{b} of the current problem, add observation a⊤x≈β\vb{a}\T\vb{x} \approx \beta using nn Givens rotations between each row jj of [R c][\mat{R}\ \vb{c}] and the new row [a⊤ β][\vb{a}\T\ \beta], and return (R_nueva, c_nueva, gamma), where gamma is the new row's last entry after rotations, satisfying ∥rnuevo∥2=∥r∥2+γ2\norm{\vb{r}_{\text{nuevo}}}^2 = \norm{\vb{r}}^2 + \gamma^2. 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 NotImplementedError
Shift+Enter to run

Summary

  • A matrix is orthogonal if square and Q⊤Q=I\mat{Q}\T\mat{Q} = \mat{I}. It preserves dot products, lengths and angles; det⁡Q=±1\det\mat{Q} = \pm 1 separates rotations from reflections, two pieces no continuous path joins. If rectangular with orthonormal columns, QQ⊤\mat{Q}\mat{Q}\T is a projector.
  • Gram–Schmidt subtracts each vector’s shadow on previous vectors and normalizes. Its record is QR, A=QR\mat{A} = \mat{Q}\mat{R}, unique with positive diagonal, where rkkr_{kk} is the distance from ak\vb{a}_k to previous vectors.
  • In floating point, cancellation subtracting shadows destroys orthogonality: CGS loses as uκ2u\kappa^2, MGS as uκu\kappa, and Householder stays at uu. Reorthogonalization (CGS2) also works.
  • Householder reflectors triangularize with mirrors orthogonal by construction; stable sign v=x+sgn⁡(x1)∥x∥e1\vb{v} = \vb{x} + \sgn(x_1)\norm{\vb{x}}\vb{e}_1 avoids cancellation, and Q\mat{Q} is stored and applied implicitly. Givens rotations zero individual entries: ideal for structured matrices and factorization updates.
  • For least squares, Rx^=Q⊤b\mat{R}\hat{\vb{x}} = \mat{Q}\T\vb{b} avoids forming A⊤A\mat{A}\T\mat{A}, whose conditioning is κ(A)2\kappa(\mat{A})^2.
Key idea
Orthogonal transformations do not amplify errors and are therefore the building blocks of reliable matrix computation: choose operations (mirrors and rotations instead of subtracting shadows or A⊤A\mat{A}\T\mat{A}) that cannot worsen their inputs.