TExcelTAD
Home › Numerical Methods › The QR Factorization

The QR Factorization

Orthogonal matrices preserve lengths, so they do not amplify errors. The QR factorization writes A=QRA = QR with QQ having orthonormal columns and RR upper triangular. It turns least squares into a triangular solve without ever forming ATAA^TA, and it is the standard method in numerical libraries.

Thin and full QR

For an m×nm \times n matrix with m≥nm \ge n:

  • Thin QR: A=Q^R^A = \hat{Q}\hat{R} with Q^\hat{Q} of size m×nm \times n (Q^TQ^=I\hat{Q}^T\hat{Q} = I) and R^\hat{R} of size n×nn \times n.
  • Full QR: A=QRA = QR with QQ square orthogonal (m×mm \times m) and RR of size m×nm \times n with zeros below row nn.

The columns of Q^\hat{Q} are an orthonormal basis of the column space of AA.

Gram-Schmidt

The classical way to build Q^\hat{Q}: orthogonalize each column of AA against the previous q\mathbf{q}'s and normalize. The coefficients form RR. The modified version subtracts projections one at a time, which is mathematically identical but much more robust in floating point.

python · try it yourself
import numpy as np

def gram_schmidt(A, modified=True):
    m, n = A.shape
    Q = np.zeros((m, n)); R = np.zeros((n, n))
    for j in range(n):
        v = A[:, j].astype(float).copy()
        for i in range(j):
            R[i, j] = Q[:, i] @ (v if modified else A[:, j])
            v -= R[i, j] * Q[:, i]
        R[j, j] = np.linalg.norm(v)
        Q[:, j] = v / R[j, j]
    return Q, R

t = np.linspace(0, 1, 60)
A = np.vander(t, 10, increasing=True)                 # ill-conditioned columns
for name, mod in (("classical", False), ("modified ", True)):
    Q, R = gram_schmidt(A, mod)
    print(f"{name} GS: ||Q^T Q - I|| = {np.linalg.norm(Q.T @ Q - np.eye(10)):.1e}, ||QR - A|| = {np.linalg.norm(Q @ R - A):.1e}")
Q, R = np.linalg.qr(A)
print(f"Householder: ||Q^T Q - I|| = {np.linalg.norm(Q.T @ Q - np.eye(10)):.1e}")
classical GS: ||Q^T Q - I|| = 1.1e-01, ||QR - A|| = 1.2e-15
modified  GS: ||Q^T Q - I|| = 1.4e-10, ||QR - A|| = 1.2e-15
Householder: ||Q^T Q - I|| = 2.2e-15

All three reproduce AA, but the classical version loses orthogonality badly, and even modified Gram-Schmidt degrades in proportion to κ(A)\kappa(A). Householder reflections keep QQ orthogonal to machine precision (Householder Reflections).

Least squares by QR

With A=Q^R^A = \hat{Q}\hat{R}, the normal equations become R^TQ^TQ^R^c=R^TQ^Ty\hat{R}^T\hat{Q}^T\hat{Q}\hat{R}\mathbf{c} = \hat{R}^T\hat{Q}^T\mathbf{y}, and since R^\hat{R} is invertible:

R^ c=Q^Ty.\hat{R}\,\mathbf{c} = \hat{Q}^T\mathbf{y}.

One matrix-vector product and one backward substitution. The conditioning is that of AA, not of ATAA^TA.

python · try it yourself
import numpy as np
from scipy.linalg import solve_triangular

t = np.linspace(0, 1, 100)
A = np.vander(t, 14, increasing=True)
y = A @ np.ones(14)                                  # exact coefficients: all ones
Q, R = np.linalg.qr(A)                               # thin QR by default
c_qr = solve_triangular(R, Q.T @ y)
c_ne = np.linalg.solve(A.T @ A, A.T @ y)
print(f"QR error: {np.max(np.abs(c_qr - 1)):.1e}")
print(f"NE error: {np.max(np.abs(c_ne - 1)):.1e}")
QR error: 4.5e-07
NE error: 1.3e+01

Cost

Householder QR costs about 2mn2−23n32mn^2 - \frac{2}{3}n^3 flops, roughly twice the normal equations when m≫nm \gg n. That price buys stability, and it is almost always worth paying.

In software

  • np.linalg.qr(A) (thin by default; mode="complete" for full), scipy.linalg.qr (with column pivoting pivoting=True for rank-revealing QR).
  • np.polyfit and scipy.linalg.lstsq(lapack_driver="gelsy") use QR; np.linalg.lstsq uses the SVD (Computing the SVD).
  • QR is also the engine of the eigenvalue algorithm (The QR Algorithm).

Exercises

Exercise 1: QR by hand

Find the thin QR factorization of A=(3142)A = \begin{pmatrix} 3 & 1 \\ 4 & 2\end{pmatrix} by Gram-Schmidt.

Answer

Q=15(3−443)Q = \frac{1}{5}\begin{pmatrix} 3 & -4 \\ 4 & 3\end{pmatrix}, R=(52.200.4)R = \begin{pmatrix} 5 & 2.2 \\ 0 & 0.4\end{pmatrix}.

Solution

r11=5r_{11} = 5, q1=(0.6,0.8)\mathbf{q}_1 = (0.6, 0.8). r12=q1⋅(1,2)=2.2r_{12} = \mathbf{q}_1\cdot(1, 2) = 2.2; v=(1,2)−2.2(0.6,0.8)=(−0.32,0.24)\mathbf{v} = (1, 2) - 2.2(0.6, 0.8) = (-0.32, 0.24), r22=0.4r_{22} = 0.4, q2=(−0.8,0.6)\mathbf{q}_2 = (-0.8, 0.6).

Exercise 2: Why orthogonal?

Why do multiplications by an orthogonal QQ not amplify errors?

Answer

∥Qx∥2=∥x∥2\lVert Q\mathbf{x}\rVert_2 = \lVert\mathbf{x}\rVert_2, so κ2(Q)=1\kappa_2(Q) = 1.

Solution

∥Qx∥2=xTQTQx=xTx\lVert Q\mathbf{x}\rVert^2 = \mathbf{x}^TQ^TQ\mathbf{x} = \mathbf{x}^T\mathbf{x}. A perturbation keeps its size after multiplication by QQ.

Exercise 3: Residual from QR (code)

With the full QR, the least-squares residual norm equals ∥(QTy)n+1:m∥\lVert(Q^T\mathbf{y})_{n+1:m}\rVert. Verify this for a line fit to 20 noisy points (seed 33).

Answer

The two numbers agree.

Solution
python · try it yourself
import numpy as np
rng = np.random.default_rng(33)
t = np.linspace(0, 1, 20); y = 2 - t + rng.normal(0, 0.1, 20)
A = np.column_stack([np.ones(20), t])
Q, R = np.linalg.qr(A, mode="complete")
qty = Q.T @ y
c = np.linalg.solve(R[:2], qty[:2])
print(round(float(np.linalg.norm(y - A @ c)), 10), round(float(np.linalg.norm(qty[2:])), 10))
0.3886842625 0.3886842625

Test yourself

Least squares via QR solves…

  1. ATAc=ATyA^TA\mathbf{c} = A^T\mathbf{y}
  2. Rc=QTyR\mathbf{c} = Q^T\mathbf{y}
  3. Qc=RyQ\mathbf{c} = R\mathbf{y}
  4. Ac=yA\mathbf{c} = \mathbf{y} exactly

Why is modified Gram-Schmidt preferred to classical?

  1. It is faster
  2. It keeps the columns of QQ much closer to orthogonal in floating point
  3. It gives a different RR in exact arithmetic
  4. It needs no square roots

The columns of Q^\hat{Q} in a thin QR of full-rank AA form…

  1. the null space of AA
  2. an orthonormal basis of the column space of AA
  3. the eigenvectors of AA
  4. the rows of AA