The Gram-Schmidt Procedure
The Gram-Schmidt procedure turns any linearly independent list of vectors into an orthonormal list with the same span. It is how orthonormal bases are built in practice, and in matrix form it is the QR factorization.
The idea
Take the vectors one at a time. Keep the first one. From each later vector, subtract its components along the directions already kept, so what remains is orthogonal to all of them. Normalize at the end (or as you go).
For independent :
Each subtracted term is the projection of onto . Two facts make it work:
- Orthogonality. By induction, are mutually orthogonal, so for each (all other terms vanish).
- Same span, no zero vectors. is minus a combination of , so . If were , would lie in the span of the earlier vectors, contradicting independence.
Consequence. Every finite-dimensional inner product space has an orthonormal basis: start from any basis and run Gram-Schmidt.
By hand in exact arithmetic
from sympy import Matrix, Rational
def gram_schmidt(vs):
us = []
for v in vs:
u = v
for w in us:
u = u - (v.dot(w) / w.dot(w)) * w
us.append(u)
return us
vs = [Matrix([1, 1, 0]), Matrix([1, 0, 1]), Matrix([0, 1, 1])]
us = gram_schmidt(vs)
for i, u in enumerate(us, 1):
print(f"u{i} =", list(u), " |u|^2 =", u.dot(u))
print("u1.u2, u1.u3, u2.u3 =", us[0].dot(us[1]), us[0].dot(us[2]), us[1].dot(us[2]))u1 = [1, 1, 0] |u|^2 = 2
u2 = [1/2, -1/2, 1] |u|^2 = 3/2
u3 = [-2/3, 2/3, 2/3] |u|^2 = 4/3
u1.u2, u1.u3, u2.u3 = 0 0 0
Dividing by the lengths gives , , . SymPy has this built in as GramSchmidt(vs, orthonormal=True).
Tip: Scaling a by a convenient constant before continuing () does not change the directions, and it keeps fractions out of hand calculations.
The matrix version:
Put in the columns of and in the columns of . Each is a combination of only, with coefficients , so
NumPy's np.linalg.qr computes this (with Householder reflections, a more stable method; its signs may differ from Gram-Schmidt, so we fix them to make positive):
import numpy as np
A = np.array([[1.0, 1.0, 0.0],
[1.0, 0.0, 1.0],
[0.0, 1.0, 1.0]])
Q, R = np.linalg.qr(A)
s = np.sign(np.diag(R)) # make diag(R) positive, as Gram-Schmidt does
Q, R = Q * s, (R.T * s).T
print("Q =\n", np.round(Q, 4))
print("R =\n", np.round(R, 4))
print("Q^T Q = I:", np.allclose(Q.T @ Q, np.eye(3)), " QR = A:", np.allclose(Q @ R, A))Q =
[[ 0.7071 0.4082 -0.5774]
[ 0.7071 -0.4082 0.5774]
[ 0. 0.8165 0.5774]]
R =
[[1.4142 0.7071 0.7071]
[0. 1.2247 0.4082]
[0. 0. 1.1547]]
Q^T Q = I: True QR = A: True
The columns of are exactly above (, , ), and holds , , .
Functions: Legendre polynomials
Gram-Schmidt works in any inner product space. Apply it to with :
from sympy import symbols, integrate, expand, Rational
x = symbols("x")
ip = lambda f, g: integrate(f * g, (x, -1, 1))
us = []
for v in [1, x, x**2, x**3]:
u = v
for w in us:
u = u - ip(v, w) / ip(w, w) * w
us.append(expand(u))
for u in us:
print(u, " scaled so p(1) = 1:", expand(u / u.subs(x, 1)))1 scaled so p(1) = 1: 1
x scaled so p(1) = 1: x
x**2 - 1/3 scaled so p(1) = 1: 3*x**2/2 - 1/2
x**3 - 3*x/5 scaled so p(1) = 1: 5*x**3/2 - 3*x/2
The scaled versions are the Legendre polynomials , used in Gaussian quadrature (the high-accuracy rule inside scipy.integrate) and in physics. SymPy prints x**2 for ; that is just its text format.
Numerical caution
Classical Gram-Schmidt in floating point can lose orthogonality badly when the input vectors are nearly dependent: tiny rounding errors in early get amplified. The modified version subtracts each projection from the running (using instead of in the inner product), which is mathematically identical but much more stable. Library QR uses Householder reflections, see Numerical Linear Algebra.
In software
- Least squares. Solving is the stable way to fit models (Least Squares).
- Eigenvalue algorithms. The QR algorithm behind
np.linalg.eigrepeats . - Graphics. Re-orthonormalizing a rotation matrix that drifted after many multiplications is a 3-vector Gram-Schmidt (see Look Rotation).
- Krylov methods and LLM tooling. Arnoldi/Lanczos iterations for huge sparse matrices orthogonalize each new vector against the previous ones.
Exercises
Exercise 1: Two vectors in
Apply Gram-Schmidt to , and normalize.
Answer
, .
Solution
Exercise 2: Three vectors in
Orthogonalize , , (no need to normalize).
Answer
, , .
Solution
from sympy import Matrix, GramSchmidt
vs = [Matrix([1, 1, 1, 1]), Matrix([1, 1, 0, 0]), Matrix([1, 0, 1, 0])]
for u in GramSchmidt(vs):
print(list(u))[1, 1, 1, 1]
[1/2, 1/2, -1/2, -1/2]
[1/2, -1/2, 1/2, -1/2]
Exercise 3: What goes wrong?
What happens if you run Gram-Schmidt on , ?
Answer
, so normalization divides by zero: the vectors are dependent.
Solution
. A zero is exactly the signal that is in the span of the earlier vectors. Practical code drops such vectors (with a tolerance) and continues, which gives an orthonormal basis of the span.
Exercise 4: Read R off the QR factorization (code)
For with columns and , find and with positive diagonal and check that .
Answer
, and .
Solution
. . , .
import numpy as np
A = np.array([[1.0, 2.0], [1.0, 0.0], [0.0, 1.0]])
Q, R = np.linalg.qr(A)
s = np.sign(np.diag(R)); Q, R = Q * s, (R.T * s).T
print(np.round(R, 4))
print(round(float(A[:, 1] @ Q[:, 0]), 4))[[1.4142 1.4142]
[0. 1.7321]]
1.4142
Test yourself
In Gram-Schmidt, what is subtracted from ?
- Its projections onto the previously built
- The average of the earlier vectors
- Its length
- Its projections onto the standard basis
In from Gram-Schmidt, is…
- diagonal
- orthogonal
- lower triangular
- upper triangular with positive diagonal
Gram-Schmidt on with produces…
- Chebyshev polynomials
- Taylor polynomials
- Legendre polynomials (up to scaling)
- sines and cosines