Module contents
Lesson 13 of 25Core 90 min

Positive definite matrices, Gram matrices and Cholesky

Positive definite matrices appear in covariances, kernels, metrics and Hessians at minima. Prove five equivalent tests, connect them to Gram matrices, use Cholesky factorization for testing and solving, and distinguish the symmetric square root from the triangular factor. Apply the factorization to multivariate Gaussian sampling.

After this lesson you can

  • Prove equivalence of the eigenvalue, pivot, leading principal minor, quadratic-form and RᵀR criteria for positive definiteness.
  • Implement Cholesky, solve systems and detect matrices that are not positive definite.
  • Relate Gram matrices, including kernel matrices, to positive semidefinite matrices.
  • Compute a matrix’s symmetric square root and compare it with its Cholesky factor.
  • Sample a multivariate Gaussian using Cholesky and use jitter when numerical definiteness fails.

Before you start

Motivation: matrices that never give a negative number

One class of symmetric matrices appears whenever you look closely at almost any machine learning system. Four examples:

  • Covariances. If x\vb{x} is a random vector with covariance matrix Σ\mat{\Sigma}, the variance of any linear combination is Var⁡(w⊤x)=w⊤Σw\Var(\vb{w}\T\vb{x}) = \vb{w}\T\mat{\Sigma}\vb{w}. A variance cannot be negative, so w⊤Σw≥0\vb{w}\T\mat{\Sigma}\vb{w} \ge 0 for every w\vb{w}.
  • Kernels. The matrix Kij=k(xi,xj)K_{ij} = k(\vb{x}_i, \vb{x}_j) of a kernel such as the Gaussian is a table of inner products in a feature space. Gaussian processes, kernel SVMs, and attention viewed as a smoother rely on that structure.
  • Hessians at a minimum. At a local minimum of a smooth function, the Hessian satisfies d⊤∇2f d≥0\vb{d}\T\hess f\,\vb{d} \ge 0 in every direction: there is no direction in which the function decreases to second order. The second-order conditions and Newton’s method revolve around this.
  • Metrics. Mahalanobis distance, the Fisher information defining the natural gradient, and the asset covariance matrix in a mean–variance portfolio are ways of measuring lengths using a matrix M\mat{M} instead of the identity: ∥x∥M2=x⊤Mx\norm{\vb{x}}_{\mat{M}}^2 = \vb{x}\T\mat{M}\vb{x}. For this to be a length, it must be positive.

In all of them, the property is the same: the quadratic form x⊤Ax\vb{x}\T\mat{A}\vb{x} is never negative. This lesson answers three practical questions. How do you check whether a particular matrix satisfies it? What do you gain when it does? (A lot: a linear system can be solved at half the cost without pivoting, and you can sample a Gaussian, evaluate its density, or whiten data.) And what do you do when rounding makes a matrix that satisfies it in theory fail on a computer?

The central tool is Cholesky factorization, A=LL⊤\mat{A} = \mat{L}\mat{L}\T. It is simultaneously the cheapest definiteness test, the fastest solver for these matrices, and the standard way to sample N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}). When you train a Gaussian process, implement a full-covariance reparameterization, or write a second-order optimizer step, you will normally end up calling Cholesky.

Definition and first examples

Two comments about the definition. First, symmetry is part of it. For an arbitrary matrix, x⊤Ax=x⊤(12(A+A⊤))x\vb{x}\T\mat{A}\vb{x} = \vb{x}\T\big(\tfrac{1}{2}(\mat{A} + \mat{A}\T)\big)\vb{x}, because the skew-symmetric part always gives zero; the quadratic form sees only the symmetric part, so we work directly with it. Second, the definition concerns all vectors: it cannot be checked by trying a few. Finite criteria are needed, and that is the first thing you will construct.

Start with an 2×22\times 2 example and the old trick of completing the square. For A=[abbc]\mat{A} = \begin{bmatrix} a & b \\ b & c \end{bmatrix} with a≠0a \ne 0,

x⊤Ax=ax12+2b x1x2+c x22=a(x1+bax2)2+(c−b2a)x22.\vb{x}\T\mat{A}\vb{x} = a x_1^2 + 2b\,x_1x_2 + c\,x_2^2 = a\Big(x_1 + \frac{b}{a}x_2\Big)^2 + \Big(c - \frac{b^2}{a}\Big)x_2^2 .

The form is a sum of two squares with weights aa and c−b2/ac - b^2/a. If both weights are positive, the sum vanishes only when both squares do, namely at x=0\vb{x} = \vb{0}. If either is negative or zero, there is an x≠0\vb{x} \ne \vb{0} with value ≤0\le 0: if it is the first, x=e1\vb{x} = \vb{e}_1 suffices; if the second, take x2=1x_2 = 1 and x1=−b/ax_1 = -b/a, which zeros the first square. Thus A≻0\mat{A} \succ 0 if and only if a>0a > 0 and ac−b2>0ac - b^2 > 0.

Those weights are not arbitrary: aa and c−b2/ac - b^2/a are exactly the pivots of Gaussian elimination on A\mat{A} (subtract b/ab/a times the first row from the second and inspect the diagonal). And aa and ac−b2ac - b^2 are the determinants of the 1×11\times 1 and 2×22\times 2 corners. This coincidence is the seed of the theorem in the next section.

QuizA first intuition
Which of these matrices are positive definite?

More than one answer may be correct.

Five tests, one verdict

The interactive shows the surface z=x⊤Axz = \vb{x}\T\mat{A}\vb{x} of a symmetric 2×22\times 2, colored red where positive and blue where negative, alongside five different definiteness tests. Move the entries and try to make the tests disagree.

InteractiveFive tests, one verdict
Move aa, bb, and cc. When A≻0\mat{A} \succ 0 the surface is a bowl that touches the plane only at the origin, and the thick curve (the form on the unit circle, whose minimum is λ2\lambda_2) lies entirely above it. Try positive entries with an indefinite matrix: a saddle appears with two lines where the form vanishes, and the marked point is a witness with x⊤Ax<0\vb{x}\T\mat{A}\vb{x} < 0. Try, unsuccessfully, to make one test say yes and another no. At the boundary (det⁡A=0\det\mat{A} = 0) all switch to the boundary verdict together.

This is no coincidence. For any size, the five tests are equivalent.

Proof

We prove a cycle of implications. For the first three use the spectral theorem: A=QΛQ⊤\mat{A} = \mat{Q}\mat{\Lambda}\mat{Q}\T with Q\mat{Q} orthogonal and Λ=diag⁡(λ1,…,λn)\mat{\Lambda} = \diag(\lambda_1, \dots, \lambda_n) real.

(1) ⇒ (2). If Aq=λq\mat{A}\vb{q} = \lambda\vb{q} with ∥q∥=1\norm{\vb{q}} = 1, then λ=λ q⊤q=q⊤Aq>0\lambda = \lambda\,\vb{q}\T\vb{q} = \vb{q}\T\mat{A}\vb{q} > 0.

(2) ⇒ (5). Take R=Λ1/2Q⊤\mat{R} = \mat{\Lambda}^{1/2}\mat{Q}\T, which is square and invertible because all λi>0\lambda_i > 0. Then R⊤R=QΛ1/2Λ1/2Q⊤=A\mat{R}\T\mat{R} = \mat{Q}\mat{\Lambda}^{1/2}\mat{\Lambda}^{1/2}\mat{Q}\T = \mat{A}.

(5) ⇒ (1). x⊤Ax=x⊤R⊤Rx=∥Rx∥2≥0\vb{x}\T\mat{A}\vb{x} = \vb{x}\T\mat{R}\T\mat{R}\vb{x} = \norm{\mat{R}\vb{x}}^2 \ge 0, and it is zero only if Rx=0\mat{R}\vb{x} = \vb{0}, which with independent columns forces x=0\vb{x} = \vb{0}.

(1) ⇒ (4). Each Ak\mat{A}_k is positive definite: for nonzero y∈Rk\vb{y} \in \R^k, pad with zeros to x=(y,0)∈Rn\vb{x} = (\vb{y}, \vb{0}) \in \R^n and observe that y⊤Aky=x⊤Ax>0\vb{y}\T\mat{A}_k\vb{y} = \vb{x}\T\mat{A}\vb{x} > 0. By (1) ⇒ (2) applied to Ak\mat{A}_k, its eigenvalues are positive, as is its determinant, their product.

(4) ⇒ (3). Elimination without exchanges only adds multiples of earlier rows to a row. These operations are lower triangular elementary matrices with ones on the diagonal and do not change any leading principal minor (the top k×kk\times k block is transformed by an k×kk\times k matrix of the same type, with determinant 1). After k−1k - 1 steps, the top k×kk\times k block is upper triangular with diagonal d1,…,dkd_1, \dots, d_k, so Δk=d1d2⋯dk\Delta_k = d_1 d_2 \cdots d_k. By induction, if all Δk\Delta_k are nonzero, every pivot dk=Δk/Δk−1d_k = \Delta_k/\Delta_{k-1} exists and row exchanges are unnecessary; if they are also positive, so are the pivots.

(3) ⇒ (1). Elimination without exchanges gives the LU factorization, written A=LDU\mat{A} = \mat{L}\mat{D}\mat{U} with L\mat{L} and U\mat{U} triangular with ones on the diagonal and D=diag⁡(d1,…,dn)\mat{D} = \diag(d_1, \dots, d_n). Since A=A⊤=U⊤DL⊤\mat{A} = \mat{A}\T = \mat{U}\T\mat{D}\mat{L}\T and this factorization is unique, U=L⊤\mat{U} = \mat{L}\T and A=LDL⊤\mat{A} = \mat{L}\mat{D}\mat{L}\T. With y=L⊤x\vb{y} = \mat{L}\T\vb{x}, which is nonzero if x\vb{x} is,

x⊤Ax=y⊤Dy=∑k=1ndk yk2>0.\vb{x}\T\mat{A}\vb{x} = \vb{y}\T\mat{D}\vb{y} = \sum_{k=1}^n d_k\, y_k^2 > 0 .

This generalizes completing the square: the pivots are the weights of the squares. Finally, LD1/2\mat{L}\mat{D}^{1/2} is lower triangular with diagonal dk>0\sqrt{d_k} > 0 and (LD1/2)(LD1/2)⊤=A(\mat{L}\mat{D}^{1/2})(\mat{L}\mat{D}^{1/2})\T = \mat{A}: it is the triangular factorization in point (5).

∎

Each test has a use. The quadratic form is the definition, used to prove that a matrix built from others (a sum, a congruence C⊤AC\mat{C}\T\mat{A}\mat{C}, a Schur complement) remains positive definite. Eigenvalues give geometric intuition and measure how definite it is: λmin⁡\lambda_{\min} is the distance (in spectral norm) to the boundary. Minors are convenient by hand in 2×22\times 2 and 3×33\times 3, but computing nn determinants is wasteful. Pivots and triangular factorization are the same thing and are used on a computer: Cholesky.

For semidefinite matrices the theorem adapts as follows: A⪰0\mat{A} \succeq 0 if and only if all eigenvalues are ≥0\ge 0, if and only if A=R⊤R\mat{A} = \mat{R}\T\mat{R} for some R\mat{R} (now without requiring independent columns). The proofs of (1) ⇒ (2) ⇒ (5) ⇒ (1) work the same way replacing >> by ≥\ge, and R\mat{R} can be chosen with rank⁡A\rank\mat{A} rows, retaining the nonzero eigenvalues.

The same question in optimization: is this a minimum?

Near a point w\vb{w}, a twice-differentiable function resembles its second-order Taylor expansion,

f(w+d)≈f(w)+∇f(w)⊤d+12 d⊤Hd,H=∇2f(w).f(\vb{w} + \vb{d}) \approx f(\vb{w}) + \grad f(\vb{w})\T\vb{d} + \tfrac{1}{2}\,\vb{d}\T\mat{H}\vb{d}, \qquad \mat{H} = \hess f(\vb{w}) .

At a critical point (∇f=0\grad f = \vb{0}) everything is determined by the Hessian’s quadratic form. If H≻0\mat{H} \succ 0, the function rises in every direction and there is a strict local minimum; if H\mat{H} is indefinite, there are downhill directions and the point is a saddle; if only semidefinite, second order is insufficient to decide. The dangerous directions are the eigenvectors with negative eigenvalues: on the interactive surface, the witness direction.

Newton’s method minimizes the quadratic model: step d\vb{d} solves Hd=−∇f\mat{H}\vb{d} = -\grad f. If H≻0\mat{H} \succ 0, that step is a descent direction, because ∇f⊤d=−∇f⊤H−1∇f<0\grad f\T\vb{d} = -\grad f\T\mat{H}\inv\grad f < 0 (the inverse of a positive definite matrix is also positive definite), and the system is solved with Cholesky. If Cholesky fails, the code has learned for free that the model is not convex at that point. The usual repair is the same one you will see later for kernels: solve with H+μI\mat{H} + \mu\mat{I}, increasing μ\mu until Cholesky succeeds. This shift interpolates between Newton (μ=0\mu = 0) and gradient descent with step 1/μ1/\mu (large μ\mu), and is the idea behind Levenberg–Marquardt and trust regions. You will study it in detail in Newton’s method; here remember that “is it positive definite?” is the question a second-order optimizer asks at every iteration.

Gram matrices: where semidefinite matrices come from

Point (5) says that being positive definite is equivalent to being a table of inner products. This interpretation deserves its own name.

You prove parts 1 and 2 in the guided exercise below. Part 3 is (2) ⇒ (5) of the previous theorem, retaining the positive eigenvalues: if G=∑i=1rλiqiqi⊤\mat{G} = \sum_{i=1}^r \lambda_i\vb{q}_i\vb{q}_i\T, the matrix R=diag⁡(λ1,…,λr) [q1⋯qr]⊤∈Rr×n\mat{R} = \diag(\sqrt{\lambda_1}, \dots, \sqrt{\lambda_r})\,[\vb{q}_1 \cdots \vb{q}_r]\T \in \R^{r\times n} satisfies R⊤R=G\mat{R}\T\mat{R} = \mat{G}, so its nn columns are the desired vectors. For part 4, equality A⊤A=B⊤B\mat{A}\T\mat{A} = \mat{B}\T\mat{B} says ∥Ax∥=∥Bx∥\norm{\mat{A}\vb{x}} = \norm{\mat{B}\vb{x}} for every x\vb{x}. The rule Ax↦Bx\mat{A}\vb{x} \mapsto \mat{B}\vb{x} is well defined on col⁡(A)\col(\mat{A}) (if Ax=Ax′\mat{A}\vb{x} = \mat{A}\vb{x}', then ∥B(x−x′)∥=∥A(x−x′)∥=0\norm{\mat{B}(\vb{x} - \vb{x}')} = \norm{\mat{A}(\vb{x} - \vb{x}')} = 0), is linear, and preserves norms; since col⁡(A)\col(\mat{A}) and col⁡(B)\col(\mat{B}) have the same dimension, so do their orthogonal complements, and any isometry between them completes U\mat{U}.

InteractiveThe Gram matrix sees only lengths and angles
Drag a1\vb{a}_1 and a2\vb{a}_2. The diagonal of G\mat{G} gives squared lengths and the off-diagonal entry gives the inner product; det⁡G\det\mat{G} equals the squared parallelogram area. Rotate or reflect both: the vectors move and G\mat{G} does not change even by a decimal. Then align a2\vb{a}_2 with a1\vb{a}_1: the area vanishes and G\mat{G} changes from definite to semidefinite.

The determinant of a Gram matrix has a precise geometric meaning. If A=QR\mat{A} = \mat{Q}\mat{R} is the QR factorization of A\mat{A} with independent columns, then

A⊤A=R⊤Q⊤QR=R⊤R,det⁡(A⊤A)=∏krkk2.\mat{A}\T\mat{A} = \mat{R}\T\mat{Q}\T\mat{Q}\mat{R} = \mat{R}\T\mat{R}, \qquad \det(\mat{A}\T\mat{A}) = \prod_{k} r_{kk}^2 .

Each rkkr_{kk} is the height of ak\vb{a}_k above the subspace of the preceding vectors (what survives Gram–Schmidt), so det⁡G\det\mat{G} is the squared nn-dimensional volume of the parallelepiped, even if the vectors live in a larger Rm\R^m. There is more: R⊤R\mat{R}\T\mat{R} with R\mat{R} upper triangular with positive diagonal is the Cholesky factorization of A⊤A\mat{A}\T\mat{A}. The Gram matrix’s Cholesky factor is the R\mat{R} factor of QR. Thus solving least squares with Cholesky on the normal equations reaches the same R\mat{R} as QR, but goes through A⊤A\mat{A}\T\mat{A}, whose condition number is the square of that of A\mat{A}.

ProofAᵀA is semidefinite, and definite with independent columns
Prove: For every A∈Rm×n\mat{A} \in \R^{m\times n}, A⊤A\mat{A}\T\mat{A} is positive semidefinite, and is positive definite if and only if the columns of A\mat{A} are linearly independent.
0
Let G=A⊤A∈Rn×n\mat{G} = \mat{A}\T\mat{A} \in \R^{n\times n} and let x∈Rn\vb{x} \in \R^n.

Step 1 of 4. What must be checked before discussing definiteness?

Kernels and covariances are Gram matrices

Two immediate consequences you will use often.

Sample covariances. If X∈Rn×d\mat{X} \in \R^{n\times d} is the data matrix and X~\tilde{\mat{X}} the same matrix with each column centered, the sample covariance is Σ^=1n−1X~⊤X~\hat{\mat{\Sigma}} = \frac{1}{n-1}\tilde{\mat{X}}\T\tilde{\mat{X}}: a Gram matrix of the centered columns. It is always semidefinite, and is definite if and only if rank⁡X~=d\rank\tilde{\mat{X}} = d. Since centering subtracts the mean, the rows of X~\tilde{\mat{X}} sum to zero and rank⁡X~≤n−1\rank\tilde{\mat{X}} \le n - 1. With n≤dn \le d examples, the sample covariance is always singular, however good the data. This is common in finance (more assets than days of useful history) and genomics.

Kernels. A kernel k(x,x′)=⟨φ(x),φ(x′)⟩k(\vb{x}, \vb{x}') = \inner{\varphi(\vb{x})}{\varphi(\vb{x}')} is an inner product between features φ(x)\varphi(\vb{x}), perhaps in an infinite-dimensional space. Its matrix Kij=k(xi,xj)K_{ij} = k(\vb{x}_i, \vb{x}_j) on any set of points is the Gram matrix of φ(x1),…,φ(xn)\varphi(\vb{x}_1), \dots, \varphi(\vb{x}_n), hence semidefinite. The converse is also true: a symmetric function whose matrices on every finite point set are all semidefinite is the inner product of some feature space. This is what makes the kernel trick work and what Mercer’s theorem formalizes. For the Gaussian kernel k(x,x′)=exp⁡ ⁣(−(x−x′)22ℓ2)k(x, x') = \exp\!\big(-\frac{(x - x')^2}{2\ell^2}\big) with distinct points, the matrix is even definite, but, as you will see at the end of the lesson, it may be so barely definite that the computer cannot tell.

Cholesky factorization

The converse is (5) ⇒ (1). You prove existence and uniqueness by induction in this section’s guided exercise. First, the algorithm, obtained by equating entries. Since L\mat{L} is lower triangular, the entry (i,j)(i, j) of LL⊤\mat{L}\mat{L}\T with i≥ji \ge j is

aij=∑k=1jℓik ℓjk.a_{ij} = \sum_{k=1}^{j} \ell_{ik}\,\ell_{jk} .

Visiting columns from left to right, each equation has only one new unknown:

ℓjj=ajj−∑k<jℓjk2,ℓij=(aij−∑k<jℓikℓjk)/ℓjj,i=j+1,…,n.\begin{aligned} \ell_{jj} &= \sqrt{a_{jj} - \textstyle\sum_{k<j} \ell_{jk}^2}, \\[4pt] \ell_{ij} &= \Big(a_{ij} - \textstyle\sum_{k<j} \ell_{ik}\ell_{jk}\Big) \Big/ \ell_{jj}, \qquad i = j+1, \dots, n . \end{aligned}

The quantity under each square root, sj=ajj−∑k<jℓjk2s_j = a_{jj} - \sum_{k<j}\ell_{jk}^2, is the pivot: sj=ℓjj2=dj=Δj/Δj−1s_j = \ell_{jj}^2 = d_j = \Delta_j/\Delta_{j-1}. This turns the algorithm into a test. If at any step sj≤0s_j \le 0, then Δj=s1⋯sj≤0\Delta_j = s_1 \cdots s_j \le 0 and the submatrix Aj\mat{A}_j is not positive definite, so neither is A\mat{A}. If the algorithm finishes, it has constructed an L\mat{L} proving that it is. There is no middle ground: Cholesky decides definiteness and also identifies the first offending leading principal submatrix.

An equivalent way of organizing the computation makes the recursive structure visible. Partition A\mat{A} into blocks:

A=[a11w⊤wA22]=[ℓ110⊤ℓI][10⊤0S][ℓ11ℓ⊤0I],ℓ11=a11,  ℓ=wℓ11,  S=A22−ww⊤a11.\mat{A} = \begin{bmatrix} a_{11} & \vb{w}\T \\ \vb{w} & \mat{A}_{22} \end{bmatrix} = \begin{bmatrix} \ell_{11} & \vb{0}\T \\ \boldsymbol{\ell} & \mat{I} \end{bmatrix} \begin{bmatrix} 1 & \vb{0}\T \\ \vb{0} & \mat{S} \end{bmatrix} \begin{bmatrix} \ell_{11} & \boldsymbol{\ell}\T \\ \vb{0} & \mat{I} \end{bmatrix}, \qquad \ell_{11} = \sqrt{a_{11}},\ \ \boldsymbol{\ell} = \frac{\vb{w}}{\ell_{11}},\ \ \mat{S} = \mat{A}_{22} - \frac{\vb{w}\vb{w}\T}{a_{11}} .

Take the square root of the pivot, divide the column, and subtract an outer product from the remaining block. What remains, S\mat{S}, is the Schur complement of a11a_{11}, and the same procedure is applied to it. This is the right-looking version of the algorithm, animated in the interactive.

InteractiveCholesky column by column
A+τI\mat{A} + \tau\mat{I}
4
2
−2
0
2
2
5
1
2
1
−2
1
6
−1
1
0
2
−1
6
1
2
1
1
1
7
Work: L\mat{L} (blue) and remaining block S\mat{S}
4
2
−2
0
2
2
5
1
2
1
−2
1
6
−1
1
0
2
−1
6
1
2
1
1
1
7
Step 0. Starting matrix
A=LL⊤,L lower triangular, ℓkk>0\mat{A} = \mat{L}\mat{L}\T,\quad \mat{L}\ \text{lower triangular},\ \ell_{kk} > 0
Each column takes three steps: square root of the pivot, division of the column, and update of the remaining block.
Pivots sk=det⁡Ak/det⁡Ak−1s_k = \det\mat{A}_k / \det\mat{A}_{k-1} (square-root scale)
s₁s₂s₃s₄s₅
step 0/14
0.00
λmin⁡(A+τI)\lambda_{\min}(\mat{A} + \tau\mat{I})0.545
det⁡Ak=s1⋯sk\det\mat{A}_k = s_1 \cdots s_k·
Cholesky completes: positive definite. λmin⁡(A+τI)=0.545\lambda_{\min}(\mat{A} + \tau\mat{I}) = 0.545.
Press play. On the right, the working matrix: computed columns of L\mat{L} in blue and, in the remaining block, the Schur complement still to factorize (highlighted just after each update). On the left, the box marks the submatrix Ak\mat{A}_k used by the algorithm so far. Choose positive diagonal, indefinite: the algorithm stops at s4=−1s_4 = -1 and identifies A4\mat{A}_4, whose determinant is −64-64. Then move τ\tau in A+τI\mat{A} + \tau\mat{I} and find the smallest shift that lets Cholesky pass: it matches −λmin⁡(A)-\lambda_{\min}(\mat{A}). With Hilbert, notice how small the pivots are.
ProofExistence and uniqueness of Cholesky by blocks
Prove: Every symmetric positive definite A∈Rn×n\mat{A} \in \R^{n\times n} has a unique factorization A=LL⊤\mat{A} = \mat{L}\mat{L}\T with L\mat{L} lower triangular and positive diagonal.
0
Induction on nn. For n=1n = 1, a11>0a_{11} > 0 and ℓ11=a11\ell_{11} = \sqrt{a_{11}} is the only positive choice. For n>1n > 1, write A=[a11w⊤wA22]\mat{A} = \begin{bmatrix} a_{11} & \vb{w}\T \\ \vb{w} & \mat{A}_{22} \end{bmatrix} and seek L=[ℓ110⊤ℓL22]\mat{L} = \begin{bmatrix} \ell_{11} & \vb{0}\T \\ \boldsymbol{\ell} & \mat{L}_{22} \end{bmatrix}.

Step 1 of 4. Why can we take ℓ11=a11\ell_{11} = \sqrt{a_{11}}?

Cost, stability, and uses

Cost. In column jj, each of the n−jn - j entries below the diagonal needs an inner product of length j−1j - 1. Summing gives about ∑j2j(n−j)≈n3/3\sum_j 2j(n - j) \approx n^3/3 floating-point operations (flops), plus nn square roots. General Gaussian elimination costs 2n3/32n^3/3: Cholesky is twice as fast because it exploits symmetry and reads and stores only half the matrix.

Stability without pivoting. LU needs row exchanges to avoid dividing by small numbers and prevent entries from growing. Cholesky does not. The diagonal equation says ∑k≤jℓjk2=ajj\sum_{k\le j}\ell_{jk}^2 = a_{jj}, so

∣ℓjk∣≤ajjpara todo k:\abs{\ell_{jk}} \le \sqrt{a_{jj}} \quad \text{para todo } k:

the entries of L\mat{L} cannot grow beyond the square root of the diagonal of A\mat{A}. This proves Cholesky is backward stable: the computed L\mat{L} is the exact factor of a matrix A+δA\mat{A} + \delta\mat{A} with ∥δA∥/∥A∥\norm{\delta\mat{A}}/\norm{\mat{A}} on the order of machine precision (Trefethen and Bau, Numerical Linear Algebra, 1997, lecture 23).

Uses. Once A\mat{A} is factorized, everything else is cheap:

  • Solve Ax=b\mat{A}\vb{x} = \vb{b}: forward substitution in Ly=b\mat{L}\vb{y} = \vb{b} and backward substitution in L⊤x=y\mat{L}\T\vb{x} = \vb{y}, about 2n22n^2 flops total. With many right-hand sides, factorization is paid for once.
  • Log determinant: log⁡det⁡A=2∑klog⁡ℓkk\log\det\mat{A} = 2\sum_k \log\ell_{kk}. Computing det⁡A\det\mat{A} directly quickly overflows or underflows (the determinant of a covariance 1000×10001000 \times 1000 with eigenvalues of order 0.010.01 is 10−200010^{-2000}); its logarithm does not.
  • Definiteness test: trying Cholesky is the cheapest reliable way to decide whether a matrix is positive definite. This is what libraries do.
  • Quadratic forms with the inverse: b⊤A−1b=∥L−1b∥2\vb{b}\T\mat{A}\inv\vb{b} = \norm{\mat{L}\inv\vb{b}}^2 using a single triangular substitution.

The factorization A=LDL⊤\mat{A} = \mat{L}\mat{D}\mat{L}\T with L\mat{L} unit diagonal is the square-root-free variant: LChol=LD1/2\mat{L}_{\text{Chol}} = \mat{L}\mat{D}^{1/2}. For indefinite symmetric matrices (such as those in constrained problems), use LDL⊤\mat{L}\mat{D}\mat{L}\T with symmetric pivoting and 2×22\times 2 blocks in D\mat{D}, the Bunch–Kaufman factorization.

Symmetric square root versus Cholesky factor

L\mat{L} is one way to “take the square root” of A\mat{A}, but not the only one. The spectral theorem gives another, with more symmetry.

Proof

Existence. B=QΛ1/2Q⊤\mat{B} = \mat{Q}\mat{\Lambda}^{1/2}\mat{Q}\T is symmetric with eigenvalues λi≥0\sqrt{\lambda_i} \ge 0, and B2=QΛ1/2Q⊤QΛ1/2Q⊤=QΛQ⊤=A\mat{B}^2 = \mat{Q}\mat{\Lambda}^{1/2}\mat{Q}\T\mat{Q}\mat{\Lambda}^{1/2}\mat{Q}\T = \mat{Q}\mat{\Lambda}\mat{Q}\T = \mat{A}. It is the matrix function f(A)f(\mat{A}) with f(t)=tf(t) = \sqrt{t}.

Uniqueness. Let B⪰0\mat{B} \succeq 0 be any matrix with B2=A\mat{B}^2 = \mat{A}. Diagonalize it: B=∑iμiuiui⊤\mat{B} = \sum_i \mu_i\vb{u}_i\vb{u}_i\T with μi≥0\mu_i \ge 0 and orthonormal ui\vb{u}_i. Then A=B2=∑iμi2uiui⊤\mat{A} = \mat{B}^2 = \sum_i \mu_i^2\vb{u}_i\vb{u}_i\T, so the eigenspace of A\mat{A} for eigenvalue λ\lambda is span⁡{ui:μi2=λ}\spn\{\vb{u}_i : \mu_i^2 = \lambda\}. Since the μi\mu_i are nonnegative, μi2=λ\mu_i^2 = \lambda is equivalent to μi=λ\mu_i = \sqrt{\lambda}: on each eigenspace of A\mat{A}, B\mat{B} acts as multiplication by λ\sqrt{\lambda}. This fully determines B\mat{B} and agrees with the constructed matrix.

∎

Condition B⪰0\mat{B} \succeq 0 is essential for uniqueness. Without it, I2\mat{I}_2 has infinitely many square roots: every reflection H\mat{H} satisfies H2=I\mat{H}^2 = \mat{I}. Keep two distinct ideas separate:

  • A root of A\mat{A} is an B\mat{B} with BB=A\mat{B}\mat{B} = \mat{A}. The symmetric semidefinite one is unique.
  • A factor of A\mat{A} is an F\mat{F} with FF⊤=A\mat{F}\mat{F}\T = \mat{A}. There are infinitely many. L\mat{L} is a factor, not a root: L2≠A\mat{L}^2 \ne \mat{A} in general.

A1/2\mat{A}^{1/2} is both a root and a factor, because it is symmetric. All square factors are related: if A=FF⊤=GG⊤\mat{A} = \mat{F}\mat{F}\T = \mat{G}\mat{G}\T with F\mat{F} invertible, then Q=F−1G\mat{Q} = \mat{F}\inv\mat{G} satisfies QQ⊤=F−1AF−⊤=I\mat{Q}\mat{Q}\T = \mat{F}\inv\mat{A}\mat{F}^{-\top} = \mat{I}, so two factors differ by an orthogonal matrix: G=FQ\mat{G} = \mat{F}\mat{Q}. In particular L=A1/2Q\mat{L} = \mat{A}^{1/2}\mat{Q} for some orthogonal Q\mat{Q}, the polar decomposition of L\mat{L}.

Sampling a Gaussian

This has a direct consequence in probability. If z∼N(0,I)\vb{z} \sim \Normal(\vb{0}, \mat{I}) and FF⊤=Σ\mat{F}\mat{F}\T = \mat{\Sigma}, then x=μ+Fz\vb{x} = \vb{\mu} + \mat{F}\vb{z} is Gaussian (an affine transformation of a Gaussian) with

E[x]=μ,Cov⁡(x)=F Cov⁡(z) F⊤=FF⊤=Σ.\E[\vb{x}] = \vb{\mu}, \qquad \Cov(\vb{x}) = \mat{F}\,\Cov(\vb{z})\,\mat{F}\T = \mat{F}\mat{F}\T = \mat{\Sigma} .

Any factor can sample N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}). In practice L\mat{L} is used because it is cheapest to compute (n3/3n^3/3 flops compared with a full spectral decomposition) and because Lz\mat{L}\vb{z} costs half as much as a dense product. It is the standard Cholesky sampling method and the basis of the reparameterization gradient: writing x=μ+Lz\vb{x} = \vb{\mu} + \mat{L}\vb{z} makes the sample depend differentiably on μ\vb{\mu} and L\mat{L}.

InteractiveSculpting a Gaussian
Drag the ends of the two semiaxes to draw the covariance ellipse (1σ1\sigma dashed, 2σ2\sigma solid). The cloud consists of the same 180 transformed samples z\vb{z}: switch between Lz\mat{L}\vb{z} and Σ1/2z\mat{\Sigma}^{1/2}\vb{z} and watch each point move. In the both mode, each gray segment joins the two images of the same z\vb{z}: the clouds fill the same ellipse, but pair points differently, because L=Σ1/2Q\mat{L} = \mat{\Sigma}^{1/2}\mat{Q} with Q\mat{Q} a rotation. Turn on coloring by z1z_1 with Lz\mat{L}\vb{z}: colors form vertical stripes, because x1=ℓ11z1x_1 = \ell_{11}z_1 does not depend on z2z_2. Rotate the ellipse to see the angle of rotation Q\mat{Q} change.

Whitening data

The inverse problem is whitening: given centered x\vb{x} with covariance Σ≻0\mat{\Sigma} \succ 0, find W\mat{W} with Cov⁡(Wx)=WΣW⊤=I\Cov(\mat{W}\vb{x}) = \mat{W}\mat{\Sigma}\mat{W}\T = \mat{I}. There are three classical choices:

WChol=L−1,WZCA=Σ−1/2,WPCA=Λ−1/2Q⊤.\mat{W}_{\text{Chol}} = \mat{L}\inv, \qquad \mat{W}_{\text{ZCA}} = \mat{\Sigma}^{-1/2}, \qquad \mat{W}_{\text{PCA}} = \mat{\Lambda}^{-1/2}\mat{Q}\T .

All three work, and by the same argument as before they are all the choices up to rotation: WΣW⊤=I\mat{W}\mat{\Sigma}\mat{W}\T = \mat{I} is equivalent to WΣ1/2\mat{W}\mat{\Sigma}^{1/2} being orthogonal, that is, W=UΣ−1/2\mat{W} = \mat{U}\mat{\Sigma}^{-1/2} with U\mat{U} orthogonal (in WPCA\mat{W}_{\text{PCA}}, U=Q⊤\mat{U} = \mat{Q}\T). Which should you choose? ZCA (zero-phase component analysis) has a distinctive property: of all whitening matrices, it leaves the whitened data most similar to the original. With W=UΣ−1/2\mat{W} = \mat{U}\mat{\Sigma}^{-1/2},

E∥x−Wx∥2=tr⁡Σ−2tr⁡(WΣ)+tr⁡(WΣW⊤)=tr⁡Σ−2tr⁡(UΣ1/2)+n,\E\norm{\vb{x} - \mat{W}\vb{x}}^2 = \tr\mat{\Sigma} - 2\tr(\mat{W}\mat{\Sigma}) + \tr(\mat{W}\mat{\Sigma}\mat{W}\T) = \tr\mat{\Sigma} - 2\tr(\mat{U}\mat{\Sigma}^{1/2}) + n,

and, with Σ1/2=∑iλi qiqi⊤\mat{\Sigma}^{1/2} = \sum_i \sqrt{\lambda_i}\,\vb{q}_i\vb{q}_i\T, tr⁡(UΣ1/2)=∑iλi qi⊤Uqi≤∑iλi\tr(\mat{U}\mat{\Sigma}^{1/2}) = \sum_i \sqrt{\lambda_i}\,\vb{q}_i\T\mat{U}\vb{q}_i \le \sum_i\sqrt{\lambda_i}, because qi⊤Uqi≤∥qi∥∥Uqi∥=1\vb{q}_i\T\mat{U}\vb{q}_i \le \norm{\vb{q}_i}\norm{\mat{U}\vb{q}_i} = 1. The maximum is attained with U=I\mat{U} = \mat{I}. That is why ZCA is used when the result should still resemble the input (for example, whitened images that still look like images; see whitening), and Cholesky when cost matters.

Löwner order and the semidefinite cone

Semidefinite matrices can be compared, but the comparison has pitfalls.

S+n\mathbb{S}^n_+ is a convex cone: if A,B⪰0\mat{A}, \mat{B} \succeq 0 and α,β≥0\alpha, \beta \ge 0, then x⊤(αA+βB)x=α x⊤Ax+β x⊤Bx≥0\vb{x}\T(\alpha\mat{A} + \beta\mat{B})\vb{x} = \alpha\,\vb{x}\T\mat{A}\vb{x} + \beta\,\vb{x}\T\mat{B}\vb{x} \ge 0. It is closed (an intersection of half-spaces {A:x⊤Ax≥0}\{\mat{A} : \vb{x}\T\mat{A}\vb{x} \ge 0\}, one for each x\vb{x}); its interior consists of positive definite matrices and its boundary of singular semidefinite ones. Optimization over it is semidefinite programming.

In 2×22\times 2 it can be drawn. A symmetric [abbc]\begin{bmatrix} a & b \\ b & c \end{bmatrix} has eigenvalues

λ1,2=a+c2±(a−c2)2+b2.\lambda_{1,2} = \frac{a + c}{2} \pm \sqrt{\Big(\frac{a - c}{2}\Big)^2 + b^2} .

With coordinates X=a−c2X = \frac{a-c}{2}, Y=bY = b, Z=a+c2Z = \frac{a+c}{2}, condition λ2≥0\lambda_2 \ge 0 reads Z≥X2+Y2Z \ge \sqrt{X^2 + Y^2}: a circular cone of 45°45° with vertical axis. Height ZZ is the eigenvalue average; distance from the axis, X2+Y2\sqrt{X^2 + Y^2}, is half their separation; and λ2=Z−X2+Y2\lambda_2 = Z - \sqrt{X^2+Y^2} measures how far the matrix is from the cone wall.

InteractiveThe cone of semidefinite matrices
Move aa, bb, and cc. Point A\mat{A} is inside the cone if and only if its distance from the axis is less than its height (the dashed circle is the cone's cross-section at that height). On the right, the ellipse {A1/2u:∥u∥≤1}\{\mat{A}^{1/2}\vb{u} : \norm{\vb{u}} \le 1\}: on touching the wall it flattens into a segment (rank 1), and outside it disappears. Choose A ⪰ B: the orange cone is B+S+2\mat{B} + \mathbb{S}^2_+, and A⪰B\mat{A} \succeq \mat{B} means A\mat{A} is inside it and the ellipse of B\mat{B} fits inside that of A\mat{A}. Then try noncomparable A and B and the squares counterexample.

The interactive shows the geometric interpretation of the order. Write E(A)={A1/2u:∥u∥≤1}\mathcal{E}(\mat{A}) = \{\mat{A}^{1/2}\vb{u} : \norm{\vb{u}} \le 1\} for A⪰0\mat{A} \succeq 0.

Proof

The support function of E(M)\mathcal{E}(\mat{M}) in direction y\vb{y} is hM(y)=max⁡∥u∥≤1y⊤M1/2u=∥M1/2y∥=y⊤Myh_{\mat{M}}(\vb{y}) = \max_{\norm{\vb{u}}\le 1} \vb{y}\T\mat{M}^{1/2}\vb{u} = \norm{\mat{M}^{1/2}\vb{y}} = \sqrt{\vb{y}\T\mat{M}\vb{y}}, by Cauchy–Schwarz. A compact convex set is the intersection of its support half-spaces {x:y⊤x≤h(y)}\{\vb{x} : \vb{y}\T\vb{x} \le h(\vb{y})\}, so one compact convex set is contained in another if and only if its support function is smaller in every direction. Here this is y⊤By≤y⊤Ay\vb{y}\T\mat{B}\vb{y} \le \vb{y}\T\mat{A}\vb{y} for every y\vb{y}.

∎

Properties that do hold, and why:

  • Congruence. If A⪰B\mat{A} \succeq \mat{B}, then C⊤AC⪰C⊤BC\mat{C}\T\mat{A}\mat{C} \succeq \mat{C}\T\mat{B}\mat{C} for any C\mat{C} (even rectangular): x⊤C⊤(A−B)Cx=(Cx)⊤(A−B)(Cx)≥0\vb{x}\T\mat{C}\T(\mat{A} - \mat{B})\mat{C}\vb{x} = (\mat{C}\vb{x})\T(\mat{A}-\mat{B})(\mat{C}\vb{x}) \ge 0.
  • Eigenvalues. If A⪰B\mat{A} \succeq \mat{B}, then λk(A)≥λk(B)\lambda_k(\mat{A}) \ge \lambda_k(\mat{B}) for each kk, with eigenvalues ordered largest to smallest. This follows directly from the Courant–Fischer minimax characterization: each λk\lambda_k is a maximum of minima of the quadratic form, and that of A\mat{A} is greater pointwise. Hence tr⁡A≥tr⁡B\tr\mat{A} \ge \tr\mat{B} and, if B⪰0\mat{B} \succeq 0, det⁡A≥det⁡B\det\mat{A} \ge \det\mat{B}.
  • Inverses. If A⪰B≻0\mat{A} \succeq \mat{B} \succ 0, then B−1⪰A−1\mat{B}\inv \succeq \mat{A}\inv. By congruence with B−1/2\mat{B}^{-1/2}, B−1/2AB−1/2⪰I\mat{B}^{-1/2}\mat{A}\mat{B}^{-1/2} \succeq \mat{I}: that matrix has eigenvalues ≥1\ge 1, its inverse B1/2A−1B1/2\mat{B}^{1/2}\mat{A}\inv\mat{B}^{1/2} has them ≤1\le 1, so is ⪯I\preceq \mat{I}, and another congruence with B−1/2\mat{B}^{-1/2} gives A−1⪯B−1\mat{A}\inv \preceq \mat{B}\inv.
  • Roots. If A⪰B⪰0\mat{A} \succeq \mat{B} \succeq 0, then A1/2⪰B1/2\mat{A}^{1/2} \succeq \mat{B}^{1/2} (Löwner–Heinz theorem: t↦tt \mapsto \sqrt{t} is “operator monotone”; see the proof in Bhatia, Matrix Analysis, 1997, chapter V).

And the pitfall: squaring does not preserve the order. With A=[2111]\mat{A} = \begin{bmatrix} 2 & 1 \\ 1 & 1 \end{bmatrix} and B=[1000]\mat{B} = \begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}, A−B=[1111]⪰0\mat{A} - \mat{B} = \begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix} \succeq 0, but

A2−B2=[5332]−[1000]=[4332],det⁡=8−9=−1<0.\mat{A}^2 - \mat{B}^2 = \begin{bmatrix} 5 & 3 \\ 3 & 2 \end{bmatrix} - \begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix} = \begin{bmatrix} 4 & 3 \\ 3 & 2 \end{bmatrix}, \qquad \det = 8 - 9 = -1 < 0 .

Scalar intuition (a≥b≥0⇒a2≥b2a \ge b \ge 0 \Rightarrow a^2 \ge b^2) fails because A\mat{A} and B\mat{B} do not commute: their ellipses have different axes. Nor is it a total order: diag⁡(2,0.5)\diag(2, 0.5) and diag⁡(0.6,1.2)\diag(0.6, 1.2) are incomparable because their difference is indefinite. And A⪰B\mat{A} \succeq \mat{B} implies nothing about off-diagonal entries (though it does about the diagonal: aii≥biia_{ii} \ge b_{ii}).

Geometry: ellipsoids and Mahalanobis distance

For Σ≻0\mat{\Sigma} \succ 0, the set

E={x:x⊤Σ−1x≤1}={Σ1/2u:∥u∥≤1}={Lu:∥u∥≤1}\mathcal{E} = \{\vb{x} : \vb{x}\T\mat{\Sigma}\inv\vb{x} \le 1\} = \{\mat{\Sigma}^{1/2}\vb{u} : \norm{\vb{u}} \le 1\} = \{\mat{L}\vb{u} : \norm{\vb{u}} \le 1\}

is an ellipsoid with semiaxes λi\sqrt{\lambda_i} in directions qi\vb{q}_i. The three descriptions agree: if x=Fu\vb{x} = \mat{F}\vb{u} with FF⊤=Σ\mat{F}\mat{F}\T = \mat{\Sigma} and F\mat{F} invertible, then x⊤Σ−1x=u⊤F⊤F−⊤F−1Fu=∥u∥2\vb{x}\T\mat{\Sigma}\inv\vb{x} = \vb{u}\T\mat{F}\T\mat{F}^{-\top}\mat{F}\inv\mat{F}\vb{u} = \norm{\vb{u}}^2. Its volume is that of the unit ball multiplied by ∣det⁡F∣=det⁡Σ\abs{\det\mat{F}} = \sqrt{\det\mat{\Sigma}}. The density level curves of N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}) are these ellipsoids translated to μ\vb{\mu} and scaled.

The Mahalanobis distance from x\vb{x} to the distribution measures how many such ellipsoids must be crossed:

dΣ(x,μ)=(x−μ)⊤Σ−1(x−μ)=∥L−1(x−μ)∥.d_{\mat{\Sigma}}(\vb{x}, \vb{\mu}) = \sqrt{(\vb{x} - \vb{\mu})\T\mat{\Sigma}\inv(\vb{x} - \vb{\mu})} = \norm{\mat{L}\inv(\vb{x} - \vb{\mu})} .

The second expression is what you implement: a forward substitution Lw=x−μ\mat{L}\vb{w} = \vb{x} - \vb{\mu} and a norm. There is never a need to form Σ−1\mat{\Sigma}\inv, which costs about 2n32n^3 flops (six times as much as Cholesky), is less accurate, and destroys triangular structure. The same approach evaluates the Gaussian log density (see Mahalanobis distance):

log⁡p(x)=−12∥L−1(x−μ)∥2−∑klog⁡ℓkk−n2log⁡(2π),\log p(\vb{x}) = -\frac{1}{2}\norm{\mat{L}\inv(\vb{x} - \vb{\mu})}^2 - \sum_{k}\log\ell_{kk} - \frac{n}{2}\log(2\pi),

because 12log⁡det⁡Σ=∑klog⁡ℓkk\frac{1}{2}\log\det\mat{\Sigma} = \sum_k \log\ell_{kk}.

The generalized eigenvalue problem

Many problems ask not for the eigenvalues of one matrix but for a comparison of two quadratic forms. In linear discriminant analysis (LDA), one seeks the direction w\vb{w} maximizing between-class scatter relative to within-class scatter, w⊤SBw/w⊤SWw\vb{w}\T\mat{S}_B\vb{w} / \vb{w}\T\mat{S}_W\vb{w}. In mechanics, vibration modes of a structure with stiffness K\mat{K} and mass M\mat{M} solve Kv=ω2Mv\mat{K}\vb{v} = \omega^2\mat{M}\vb{v}. Canonical correlation has the same form.

One could multiply by B−1\mat{B}\inv and solve B−1Av=λv\mat{B}\inv\mat{A}\vb{v} = \lambda\vb{v}, but B−1A\mat{B}\inv\mat{A} is not symmetric and everything the spectral theorem gives would be lost. Cholesky fixes this. With B=LL⊤\mat{B} = \mat{L}\mat{L}\T and the change of variable y=L⊤v\vb{y} = \mat{L}\T\vb{v},

AL−⊤y=λLy  ⟺  L−1AL−⊤⏟C y=λy.\mat{A}\mat{L}^{-\top}\vb{y} = \lambda\mat{L}\vb{y} \quad\iff\quad \underbrace{\mat{L}\inv\mat{A}\mat{L}^{-\top}}_{\mat{C}}\,\vb{y} = \lambda\vb{y} .

C\mat{C} is symmetric, so the generalized problem inherits everything:

Proof

Let yi\vb{y}_i be orthonormal eigenvectors of C\mat{C} and vi=L−⊤yi\vb{v}_i = \mat{L}^{-\top}\vb{y}_i. Then Avi=LCyi=λiLyi=λiLL⊤vi=λiBvi\mat{A}\vb{v}_i = \mat{L}\mat{C}\vb{y}_i = \lambda_i\mat{L}\vb{y}_i = \lambda_i\mat{L}\mat{L}\T\vb{v}_i = \lambda_i\mat{B}\vb{v}_i, and vi⊤Bvj=yi⊤L−1LL⊤L−⊤yj=yi⊤yj=δij\vb{v}_i\T\mat{B}\vb{v}_j = \vb{y}_i\T\mat{L}\inv\mat{L}\mat{L}\T\mat{L}^{-\top}\vb{y}_j = \vb{y}_i\T\vb{y}_j = \delta_{ij}. The same gives vi⊤Avj=yi⊤Cyj=λiδij\vb{v}_i\T\mat{A}\vb{v}_j = \vb{y}_i\T\mat{C}\vb{y}_j = \lambda_i\delta_{ij}. For the quotient, with x=L−⊤y\vb{x} = \mat{L}^{-\top}\vb{y},

x⊤Axx⊤Bx=y⊤Cyy⊤y,\frac{\vb{x}\T\mat{A}\vb{x}}{\vb{x}\T\mat{B}\vb{x}} = \frac{\vb{y}\T\mat{C}\vb{y}}{\vb{y}\T\vb{y}},

which is the ordinary Rayleigh quotient of C\mat{C}, bounded by its extreme eigenvalues.

∎

The matrix V\mat{V} simultaneously diagonalizes two quadratic forms by congruence. Geometrically: in the metric of B\mat{B}, where the “unit sphere” is the ellipsoid x⊤Bx=1\vb{x}\T\mat{B}\vb{x} = 1, the form of A\mat{A} looks like an ordinary symmetric matrix. Generalized eigenvectors are not perpendicular in the Euclidean sense, but are in the sense of B\mat{B}.

InteractiveGeneralized Rayleigh and Cholesky reduction
Point x\vb{x} moves on the ellipse x⊤Bx=1\vb{x}\T\mat{B}\vb{x} = 1, so its quotient is simply x⊤Ax\vb{x}\T\mat{A}\vb{x}; the plot below shows it by direction. Drag it to the maximum and minimum: they occur at v1\vb{v}_1 and v2\vb{v}_2, which are not at 90°90° but satisfy v1⊤Bv2=0\vb{v}_1\T\mat{B}\vb{v}_2 = 0. At those points, the two level curves have parallel tangents (gray lines). Turn on y=L⊤x\vb{y} = \mat{L}\T\vb{x}: the ellipse of B\mat{B} becomes the unit circle, eigenvectors become perpendicular, and the problem is that of symmetric C\mat{C}.

In code there is no need to perform the reduction by hand: scipy.linalg.eigh(A, B) solves the symmetric generalized problem by calling LAPACK routines in the sygv family, which do exactly this (Cholesky of B\mat{B}, reduction to C\mat{C}, and standard problem) and return vi\vb{v}_i normalized with V⊤BV=I\mat{V}\T\mat{B}\mat{V} = \mat{I}.

When rounding breaks definiteness: jitter

Some matrices are positive definite in theory but not on a computer. A Gaussian kernel matrix on nearby points is the canonical example: if two points are very close, their rows are nearly equal and the matrix is nearly singular. Its smallest eigenvalue may be 10−2010^{-20}, far below double-precision accuracy, u≈1.1×10−16u \approx 1.1\times 10^{-16} relative to the matrix scale. After rounding, the small computed eigenvalues are noise of order u∥K∥u\norm{\mat{K}}, many of them negative. Cholesky fails or, worse, finishes with final pivots that are pure noise. The same happens to sample covariances with n≈dn \approx d and approximate Hessians.

The standard remedy is jitter: add a small multiple of the identity. Since K\mat{K} and I\mat{I} commute, K+εI\mat{K} + \eps\mat{I} has the eigenvalues of K\mat{K} shifted by ε\eps:

λi(K+εI)=λi(K)+ε.\lambda_i(\mat{K} + \eps\mat{I}) = \lambda_i(\mat{K}) + \eps .

An ε\eps several times larger than rounding noise, whose magnitude is of order n u max⁡iKiin\,u\,\max_i K_{ii}, restores definiteness. The price is solving a different problem: in a Gaussian process, K+εI\mat{K} + \eps\mat{I} is exactly the covariance matrix of observations with noise variance ε\eps, so jitter amounts to assuming some data noise. The model no longer interpolates exactly: with α=(K+εI)−1y\vb{\alpha} = (\mat{K} + \eps\mat{I})\inv\vb{y}, the residual is y−Kα=εα\vb{y} - \mat{K}\vb{\alpha} = \eps\vb{\alpha}. You will see in the code cell that the smaller ε\eps is, the better the data are interpolated, but the larger (and less stable) the coefficients become. Choose it rather than setting it blindly. See Cholesky in finite precision and Gaussian processes for details.

Before jitter, symmetrize. A matrix that should be symmetric but was computed as a product of several matrices may have rounding differences between KijK_{ij} and KjiK_{ji}. np.linalg.cholesky and scipy.linalg.cholesky read only one triangle and do not warn if the other differs: they factor a matrix that is not yours. K = (K + K.T) / 2 costs almost nothing and avoids the surprise.

Implementation from scratch

Start with Cholesky in column form. Each column uses an inner product for the diagonal and a matrix–vector product for the rest; if the pivot is not positive, the error identifies the principal submatrix that revealed it.

[ ]Cholesky from scratch, as factorization and testBrowser
import numpy as np

def cholesky(A):
    """Factor L triangular inferior con A = L @ L.T. Lanza ValueError si A no es definida positiva."""
    A = np.asarray(A, dtype=float)
    n = A.shape[0]
    L = np.zeros_like(A)
    for j in range(n):
        s = A[j, j] - L[j, :j] @ L[j, :j]          # pivote s_j
        if s <= 0:
            raise ValueError(f"pivote s_{j+1} = {s:.3g} <= 0: A no es definida positiva (falla A_{j+1})")
        L[j, j] = np.sqrt(s)
        # la columna j por debajo de la diagonal, de una vez
        L[j+1:, j] = (A[j+1:, j] - L[j+1:, :j] @ L[j, :j]) / L[j, j]
    return L

rng = np.random.default_rng(0)
M = rng.standard_normal((6, 6))
A = M.T @ M + 0.1 * np.eye(6)      # una matriz de Gram más algo de diagonal: definida positiva
L = cholesky(A)
print("‖A − L Lᵀ‖ =", np.linalg.norm(A - L @ L.T))
print("¿Coincide con NumPy?", np.allclose(L, np.linalg.cholesky(A)))

# dos matrices que no son definidas positivas (la segunda es la del interactivo)
for B in ([[1, 2], [2, 1]],
          [[4, 2, -2, 0, 2], [2, 5, 1, 2, 1], [-2, 1, 6, -1, 1], [0, 2, -1, 1, 1], [2, 1, 1, 1, 7]]):
    try:
        cholesky(B)
    except ValueError as e:
        print(e)

With L\mat{L} in hand, solving means chaining two triangular substitutions, and the log determinant comes from the diagonal.

[ ]Solve systems and compute log det with LBrowser
def forward_sub(L, b):
    """Resuelve L y = b con L triangular inferior."""
    y = np.zeros(len(b))
    for i in range(len(b)):
        y[i] = (b[i] - L[i, :i] @ y[:i]) / L[i, i]
    return y

def back_sub(U, y):
    """Resuelve U x = y con U triangular superior."""
    n = len(y)
    x = np.zeros(n)
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - U[i, i+1:] @ x[i+1:]) / U[i, i]
    return x

def chol_solve(L, b):
    return back_sub(L.T, forward_sub(L, b))

b = rng.standard_normal(6)
x = chol_solve(L, b)
print("residuo ‖A x − b‖ =", np.linalg.norm(A @ x - b))
logdet = 2 * np.sum(np.log(np.diag(L)))
print("log det A (Cholesky):", logdet, "   NumPy slogdet:", np.linalg.slogdet(A)[1])

Now sampling. With 200,000 samples, the empirical covariance should approach Σ\mat{\Sigma} with relative error of order 1/n1/\sqrt{n}.

[ ]Sample N(μ, Σ) as μ + L zBrowser
mu = np.array([1.0, -2.0, 0.5])
Sigma = np.array([[4.0, 2.0, 0.6],
                  [2.0, 3.0, -0.5],
                  [0.6, -0.5, 1.0]])
Ls = cholesky(Sigma)
n = 200_000
Z = rng.standard_normal((n, 3))
X = mu + Z @ Ls.T                    # cada fila es mu + L z
print("media empírica:", X.mean(axis=0).round(3))
print("covarianza empírica:\n", np.cov(X, rowvar=False).round(3))
print("error relativo:", np.linalg.norm(np.cov(X, rowvar=False) - Sigma) / np.linalg.norm(Sigma))

The symmetric root comes from the spectral decomposition. Verify that sampling with it gives the same covariance, that Q=Σ−1/2L\mat{Q} = \mat{\Sigma}^{-1/2}\mat{L} is orthogonal, and that nevertheless each z\vb{z} ends up in a different place.

[ ]Symmetric root versus CholeskyBrowser
def sqrtm_psd(A):
    lam, Q = np.linalg.eigh(A)
    return (Q * np.sqrt(np.clip(lam, 0, None))) @ Q.T

S = sqrtm_psd(Sigma)
print("‖S S − Σ‖ =", np.linalg.norm(S @ S - Sigma))
print("S simétrica:", np.allclose(S, S.T), "| L simétrica:", np.allclose(Ls, Ls.T))
Q = np.linalg.solve(S, Ls)           # L = S Q
print("‖QᵀQ − I‖ =", np.linalg.norm(Q.T @ Q - np.eye(3)), "  det Q =", np.linalg.det(Q).round(6))
XS = mu + Z @ S.T
print("misma covarianza:", np.allclose(np.cov(XS, rowvar=False), np.cov(X, rowvar=False), atol=0.05))
print("distancia media entre parejas ‖Lz − Sz‖:", np.linalg.norm(X - XS, axis=1).mean().round(3))

And whitening: both methods produce identity covariance, but ZCA leaves the data closer to the original, as the trace inequality predicts.

[ ]Cholesky whitening versus ZCABrowser
Xc = X - X.mean(axis=0)
C = np.cov(Xc, rowvar=False)
# aquí sí formamos las inversas: son 3x3 y se aplican a 200 000 filas
W_chol = np.linalg.inv(cholesky(C))
W_zca = np.linalg.inv(sqrtm_psd(C))
for name, W in [("Cholesky", W_chol), ("ZCA", W_zca)]:
    Y = Xc @ W.T
    print(f"{name:9s} cov ≈ I: {np.allclose(np.cov(Y, rowvar=False), np.eye(3), atol=1e-8)}   "
          f"E‖x − Wx‖² = {np.mean(np.sum((Xc - Y)**2, axis=1)):.4f}")

Kernel matrices and jitter

The Gaussian kernel matrix with ℓ=0.4\ell = 0.4 on 60 equally spaced points of [0,1][0, 1] is positive definite in exact arithmetic. Look at what the computer sees.

[ ]A Gaussian kernel the computer cannot see as definiteBrowser
def rbf(x, y, ell):
    return np.exp(-0.5 * (x[:, None] - y[None, :])**2 / ell**2)

xs = np.linspace(0, 1, 60)
K = rbf(xs, xs, 0.4)
lam = np.linalg.eigvalsh(K)
print("los tres autovalores calculados más pequeños:", lam[:3])
print("autovalores calculados < 0:", np.sum(lam < 0), "de", len(lam))
for name, chol in [("propia", cholesky), ("NumPy ", np.linalg.cholesky)]:
    try:
        Lk = chol(K)
        if not np.all(np.isfinite(Lk)):
            print(f"Cholesky {name} sin jitter: no lanza ningún error, ¡pero L contiene NaN!")
        else:
            piv = np.diag(Lk)**2
            print(f"Cholesky {name} sin jitter: termina, pero el pivote menor es {piv.min():.1e} (ruido de redondeo)")
    except (ValueError, np.linalg.LinAlgError):
        print(f"Cholesky {name} sin jitter: falla (algún pivote calculado es <= 0)")

What happens depends on the machine and library (the summation order changes rounding): sometimes a pivot is negative and Cholesky stops; sometimes all are positive but rounding-sized, and the factor “works” even though it is garbage; and there is a third case, which you will see in the browser. NumPy learns that LAPACK failed through floating-point exception flags, which WebAssembly lacks: in Pyodide, np.linalg.cholesky (and also np.linalg.inv on a singular matrix) returns a matrix full of NaN instead of raising LinAlgError, even for something as clearly indefinite as [1221]\begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix}. scipy.linalg.cholesky does raise the error. The last two cases are worse than the first because they give no warning: always check that the factor is finite, as chol_ok does in the next cell.

Now sweep jitter and inspect the tradeoff: from which ε\eps the result is usable, the size of coefficients α\vb{\alpha}, and how well the data are interpolated. In exact arithmetic, the residual is ε∥α∥\eps\norm{\vb{\alpha}} (the diagonal scale here is 1): check it in each row.

[ ]The price of jitterBrowser
y = np.sin(2 * np.pi * xs)
scale = np.mean(np.diag(K))

def chol_ok(M):
    """Factor de NumPy, o None si Cholesky falla (con excepción o, en el navegador, con NaN silenciosos)."""
    try:
        Lk = np.linalg.cholesky(M)
    except np.linalg.LinAlgError:
        return None
    return Lk if np.all(np.isfinite(Lk)) else None

for eps in [1e-16, 1e-14, 1e-12, 1e-10, 1e-8, 1e-6, 1e-4, 1e-2]:
    Lk = chol_ok(K + eps * scale * np.eye(len(xs)))
    if Lk is None:
        print(f"ε = {eps:.0e}: Cholesky falla")
        continue
    alpha = chol_solve(Lk, y)
    print(f"ε = {eps:.0e}: ‖α‖ = {np.linalg.norm(alpha):9.3e}   residuo ‖y − Kα‖ = {np.linalg.norm(y - K @ alpha):.2e}")

Notice the magnitude of ∥α∥\norm{\vb{\alpha}} with the smallest usable jitter: enormous coefficients that cancel each other, a sign of an ill-conditioned problem. In practice use somewhat more than the minimum jitter (or estimate observation noise as another hyperparameter) and check that predictions do not change when it moves.

The professional version

NumPy and SciPy wrap LAPACK routines (potrf for Cholesky, potrs to solve with the factor). Correspondences with what you wrote:

From scratchLibraryNote
cholesky(A)np.linalg.cholesky(A), scipy.linalg.cholesky(A, lower=True)raise LinAlgError if not positive definite (NumPy in the browser returns NaN)
chol_solve(L, b)scipy.linalg.cho_factor + cho_solvereuse the factor for many right-hand sides
forward_sub, back_subscipy.linalg.solve_triangular(L, b, lower=True)Mahalanobis, log density
sqrtm_psd(A)scipy.linalg.sqrtm(A)general method (Schur); for symmetric matrices, eigh is more direct
Cholesky reductionscipy.linalg.eigh(A, B)symmetric generalized problem
2 * sum(log(diag(L)))np.linalg.slogdet(A)this uses LU; with L\mat{L} already computed, the sum is free
[ ]The same with SciPy and the upper-triangle trapBrowser
import scipy.linalg as sla

c, low = sla.cho_factor(Sigma, lower=True)
xx = sla.cho_solve((c, low), b[:3])
print("cho_solve resuelve:", np.allclose(Sigma @ xx, b[:3]))

# Mahalanobis sin formar la inversa
Lnp = np.linalg.cholesky(Sigma)
d = X[:5] - mu
w = sla.solve_triangular(Lnp, d.T, lower=True)
print("Mahalanobis (triangular):", np.sqrt(np.sum(w**2, axis=0)).round(4))
print("Mahalanobis (con inversa):", np.sqrt(np.einsum("ij,jk,ik->i", d, np.linalg.inv(Sigma), d)).round(4))
print("sqrtm de SciPy ≈ la nuestra:", np.allclose(sla.sqrtm(Sigma), S))

# np.linalg.cholesky solo mira el triángulo inferior
basura = np.array([[4.0, 100.0],
                   [2.0, 5.0]])            # no es simétrica
print("Cholesky de una matriz no simétrica, sin error:\n", np.linalg.cholesky(basura))
[ ]Generalized eigenproblem: SciPy versus reductionBrowser
Ag = np.array([[2.0, 1.0, 0.0], [1.0, 3.0, 1.0], [0.0, 1.0, 1.0]])
Bg = Sigma
lam_g, V = sla.eigh(Ag, Bg)
Lb = np.linalg.cholesky(Bg)
Y = sla.solve_triangular(Lb, Ag, lower=True)            # L⁻¹ A
Cg = sla.solve_triangular(Lb, Y.T, lower=True)          # L⁻¹ (L⁻¹ A)ᵀ = L⁻¹ A L⁻ᵀ
print("autovalores (SciPy):    ", lam_g.round(6))
print("autovalores (reducción):", np.linalg.eigvalsh(Cg).round(6))
print("VᵀBV = I:", np.allclose(V.T @ Bg @ V, np.eye(3)), "  VᵀAV diagonal:", np.allclose(V.T @ Ag @ V, np.diag(lam_g)))
print("VᵀV, que no es la identidad:\n", (V.T @ V).round(3))

In PyTorch, torch.linalg.cholesky and torch.linalg.cholesky_ex (which returns an error code instead of raising an exception, useful inside a training loop) do the same on GPU, and torch.distributions.MultivariateNormal accepts scale_tril=L directly to avoid refactorizing at every step.

Common mistakes

Exercises

NumericA Cholesky entry
Compute entry ℓ22\ell_{22} of the Cholesky factor of A=[4225]\mat{A} = \begin{bmatrix} 4 & 2 \\ 2 & 5 \end{bmatrix}.
NumericHow much coupling is possible?
What is the supremum of ∣t∣\abs{t} for which [2tt2]\begin{bmatrix} 2 & t \\ t & 2 \end{bmatrix} is positive definite?
NumericA determinant using Cholesky
Compute det⁡A\det\mat{A} using Cholesky factorization, with A=[9333513111]\mat{A} = \begin{bmatrix} 9 & 3 & 3 \\ 3 & 5 & 1 \\ 3 & 1 & 11 \end{bmatrix}.
QuizWhat respects Löwner order
Let A⪰B⪰0\mat{A} \succeq \mat{B} \succeq 0. Which statements always hold?

More than one answer may be correct.

QuizSylvester with zero minors
A symmetric 3×33\times 3 matrix has Δ1=0\Delta_1 = 0, Δ2=0\Delta_2 = 0 and Δ3=0\Delta_3 = 0. What can you conclude?
NumericMahalanobis distance without an inverse
With Σ=[4225]\mat{\Sigma} = \begin{bmatrix} 4 & 2 \\ 2 & 5 \end{bmatrix}, μ=0\vb{\mu} = \vb{0} and x=(2,3)\vb{x} = (2, 3), compute the Mahalanobis distance dΣ(x,μ)d_{\mat{\Sigma}}(\vb{x}, \vb{\mu}) by solving a triangular system.
NumericThe maximum of a quotient of forms
Compute max⁡x≠0x⊤Axx⊤Bx\max_{\vb{x} \ne \vb{0}} \dfrac{\vb{x}\T\mat{A}\vb{x}}{\vb{x}\T\mat{B}\vb{x}} for A=[2112]\mat{A} = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix} and B=[1004]\mat{B} = \begin{bmatrix} 1 & 0 \\ 0 & 4 \end{bmatrix}.
QuizRoot or factor?
Let Σ≻0\mat{\Sigma} \succ 0 have Cholesky factor L\mat{L} and symmetric root S=Σ1/2\mat{S} = \mat{\Sigma}^{1/2}. Which statement is correct?
QuizWhat jitter does
A 500×500500\times 500 kernel matrix K\mat{K} makes np.linalg.cholesky fail, although it is positive definite in theory. You add εI\eps\mat{I} with ε=10−6max⁡iKii\eps = 10^{-6}\max_i K_{ii} and it works. Which statement is correct?
CodeDefiniteness test and Gaussian sampling
Implement two functions. is_pd(A, tol=1e-12) returns True if A is symmetric (use np.allclose(A, A.T)) and positive definite, by attempting your own Cholesky factorization: return False as soon as a pivot satisfies sj≤s_j \le tol ⋅max⁡i∣aii∣\cdot \max_i \abs{a_{ii}} (so singular semidefinite matrices return False even when rounding leaves a tiny positive pivot). sample_mvn(mu, Sigma, n, rng) returns an n×dn\times d array whose rows are samples from N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}), generated as μ+Lz\vb{\mu} + \mat{L}\vb{z} with rng.standard_normal. You may use np.linalg.cholesky in sample_mvn, but not in is_pd.
import numpy as np

def is_pd(A, tol=1e-12):
  """True si A es simétrica definida positiva (con tu propia Cholesky)."""
  A = np.asarray(A, dtype=float)
  # tu código
  ...

def sample_mvn(mu, Sigma, n, rng):
  """Array (n, d) de muestras de N(mu, Sigma)."""
  # tu código
  raise NotImplementedError
Shift+Enter to run
ProofPositive pivots imply positive definiteness
Prove: If Gaussian elimination without exchanges on a symmetric A\mat{A} produces pivots d1,…,dnd_1, \dots, d_n that are all positive, then A≻0\mat{A} \succ 0.
0
Elimination without exchanges gives A=LU\mat{A} = \mat{L}\mat{U} with L\mat{L} unit lower triangular and U\mat{U} upper triangular with diagonal d1,…,dnd_1, \dots, d_n.

Step 1 of 3. Write U=DU~\mat{U} = \mat{D}\tilde{\mat{U}} with D=diag⁡(dk)\mat{D} = \diag(d_k). How are U~\tilde{\mat{U}} and L\mat{L} related?

Summary

Key idea
A symmetric matrix is positive definite when its quadratic form gives only positive values. Eigenvalues, pivots, leading principal minors, and factorization A=LL⊤\mat{A} = \mat{L}\mat{L}\T are five faces of the same property, and Cholesky is the cheapest way to test and exploit it.
  • Five equivalent tests. Positive quadratic form, positive eigenvalues, positive pivots, positive leading principal minors, and A=R⊤R\mat{A} = \mat{R}\T\mat{R} with R\mat{R} having independent columns. For semidefinite matrices, Sylvester works only with all principal minors.
  • Gram = semidefinite. A⊤A⪰0\mat{A}\T\mat{A} \succeq 0, definite if and only if the columns are independent; every semidefinite matrix is a table of inner products. Covariances and kernels are such by construction. The Cholesky factor of A⊤A\mat{A}\T\mat{A} is the R\mat{R} of QR.
  • Cholesky. n3/3n^3/3 flops, no pivoting, stable; failure identifies the offending submatrix Ak\mat{A}_k. It solves systems and gives log⁡det⁡\log\det and Mahalanobis distance without inversion.
  • Root versus factor. A1/2\mat{A}^{1/2} is the unique semidefinite root; factors FF⊤=A\mat{F}\mat{F}\T = \mat{A} are infinite and differ by an orthogonal matrix. All can sample μ+Fz\vb{\mu} + \mat{F}\vb{z}; for whitening, ZCA distorts the data least.
  • Löwner order. A⪰B\mat{A} \succeq \mat{B} is inclusion of ellipses. It respects congruences, eigenvalues, trace, determinant, inverses (in reverse), and roots, but not squares.
  • In practice. The generalized problem Av=λBv\mat{A}\vb{v} = \lambda\mat{B}\vb{v} reduces through Cholesky to a symmetric one with B\mat{B}-orthogonal eigenvectors; theoretically semidefinite matrices are symmetrized and given jitter, understanding that this assumes noise.