AnyLearn
All lessons
Mathadvanced

Iterative Solvers: From Jacobi to Preconditioned Conjugate Gradient

When a matrix is too large to factor, solve Ax = b by improving a guess. See why Jacobi stalls on fine grids, how Krylov methods and conjugate gradient use the whole history, why iterations scale with the square root of the condition number, what preconditioning buys, and how to set and check tolerances.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 10

When factoring is not an option

The previous lesson ended at fill-in: factor a large sparse matrix and the factors can hold far more nonzeros than the matrix itself. Iterative methods avoid factoring entirely. They start from a guess x0\mathbf{x}_0 and improve it, and the only thing most of them ever do with AA is multiply it by a vector.

That single requirement has large consequences:

  • Memory is O(nnz)O(\text{nnz}), the storage of AA plus a handful of vectors, with no fill-in at all.
  • AA need not be stored. Anything that can compute AvA\mathbf{v}, a stencil, a simulation, a product of operators, is enough; SciPy expresses this as a LinearOperator.
  • Accuracy is a dial. Stop at a residual of 10−310^{-3} if that is all the model justifies, and pay for three digits instead of sixteen.

Key idea: a direct method's cost is fixed by the matrix's structure. An iterative method's cost is the number of iterations times the cost of one product, and the whole subject is about making that number small.

Sign in free to save your progress and earn certificates.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. When factoring is not an option

The previous lesson ended at fill-in: factor a large sparse matrix and the factors can hold far more nonzeros than the matrix itself. Iterative methods avoid factoring entirely. They start from a guess x0\mathbf{x}_0 and improve it, and the only thing most of them ever do with AA is multiply it by a vector.

That single requirement has large consequences:

  • Memory is O(nnz)O(\text{nnz}), the storage of AA plus a handful of vectors, with no fill-in at all.
  • AA need not be stored. Anything that can compute AvA\mathbf{v}, a stencil, a simulation, a product of operators, is enough; SciPy expresses this as a LinearOperator.
  • Accuracy is a dial. Stop at a residual of 10−310^{-3} if that is all the model justifies, and pay for three digits instead of sixteen.

Key idea: a direct method's cost is fixed by the matrix's structure. An iterative method's cost is the number of iterations times the cost of one product, and the whole subject is about making that number small.

2. Splitting methods: Jacobi and Gauss-Seidel

The oldest iterations split A=D+L+UA = D + L + U into its diagonal, strictly lower and strictly upper parts, and solve the easy part exactly at each step. Jacobi uses only the diagonal:

xk+1=xk+D−1(b−Axk)\mathbf{x}_{k+1} = \mathbf{x}_k + D^{-1}\left(\mathbf{b} - A\mathbf{x}_k\right)

Gauss-Seidel uses D+LD + L, which in code means overwriting each unknown as soon as its new value is known. Both have the form xk+1=Gxk+c\mathbf{x}_{k+1} = G\mathbf{x}_k + \mathbf{c}, so the error obeys ek+1=G ek\mathbf{e}_{k+1} = G\,\mathbf{e}_k and after kk steps is Gke0G^k \mathbf{e}_0.

Definition: the spectral radius ρ(G)\rho(G) is the largest magnitude among the eigenvalues of GG. A splitting iteration converges from every starting guess if and only if ρ(G)<1\rho(G) < 1, and the error then shrinks by roughly a factor ρ(G)\rho(G) per step (Demmel, Applied Numerical Linear Algebra, chapter 6).

So the iteration count to reduce the error by a factor tol\text{tol} is about ln⁡(tol)/ln⁡ρ(G)\ln(\text{tol}) / \ln \rho(G). Everything depends on how close ρ\rho is to 1.

3. Why Jacobi stalls on fine grids

Take the model problem used throughout this lesson: the 5-point Laplacian on an N×NN \times N grid, n=N2n = N^2 unknowns, five nonzeros per row. For this matrix Jacobi's spectral radius is known exactly, ρ=cos⁡ ⁣(π/(N+1))\rho = \cos\!\big(\pi/(N+1)\big) (Demmel, chapter 6), and since ln⁡cos⁡θ≈−θ2/2\ln\cos\theta \approx -\theta^2/2,

k≈2(N+1)2π2 ln⁡1tolk \approx \frac{2(N+1)^2}{\pi^2}\,\ln\frac{1}{\text{tol}}

Predicted and measured iterations to a residual of 10−810^{-8}:

NNρ\rhoPredictedMeasured
160.98297310731064
320.99547240594020
640.9988321576515599
1280.9997036211261430

Halving the grid spacing multiplies the work per iteration by 4 and the iteration count by 4. The slow components are the smooth, long-wavelength errors, which a local averaging step barely touches. Multigrid methods exploit exactly that, by correcting smooth errors on coarser grids, but they are beyond this lesson.

4. Krylov subspaces: use the whole history

Jacobi forgets everything except the current iterate. After kk matrix-vector products, though, you have seen every vector in the Krylov subspace

Kk(A,r0)=span⁡{r0,  Ar0,  A2r0,  …,  Ak−1r0}\mathcal{K}_k(A, \mathbf{r}_0) = \operatorname{span}\{\mathbf{r}_0,\; A\mathbf{r}_0,\; A^2\mathbf{r}_0,\; \dots,\; A^{k-1}\mathbf{r}_0\}

where r0=b−Ax0\mathbf{r}_0 = \mathbf{b} - A\mathbf{x}_0. A Krylov method picks the best xk\mathbf{x}_k in x0+Kk\mathbf{x}_0 + \mathcal{K}_k by some criterion, for the same matrix-vector cost as Jacobi. Equivalently, xk−x⋆=p(A) (x0−x⋆)\mathbf{x}_k - \mathbf{x}^\star = p(A)\,(\mathbf{x}_0 - \mathbf{x}^\star) for a polynomial pp of degree kk with p(0)=1p(0) = 1, and the method chooses the polynomial. A splitting method is stuck with one fixed choice: for Jacobi on a matrix with constant diagonal dd, it is p(z)=(1−z/d)kp(z) = (1 - z/d)^k.

The conjugate gradient method (Hestenes and Stiefel, 1952) applies when AA is symmetric positive definite. It chooses the iterate that minimises the error in the AA-norm, ∥e∥A=e⊤A e\|\mathbf{e}\|_A = \sqrt{\mathbf{e}^\top A\,\mathbf{e}}, over the whole subspace, using a recurrence that needs only the last few vectors. In exact arithmetic it would finish in at most nn steps (Trefethen and Bau, Lecture 38); in practice it is stopped far earlier.

5. Conjugate gradient, line by line

The whole algorithm fits in a dozen lines. One product with AA per step, two inner products, three vector updates:

import numpy as np
import scipy.sparse as sp

def conjugate_gradient(A, b, rtol=1e-8, maxiter=10_000):
    x = np.zeros_like(b)
    r = b - A @ x                  # residual
    p = r.copy()                   # search direction
    rr = r @ r
    for k in range(1, maxiter + 1):
        Ap = A @ p                 # the only use of A: one product per step
        alpha = rr / (p @ Ap)      # exact line search along p
        x += alpha * p
        r -= alpha * Ap
        rr_new = r @ r
        if np.sqrt(rr_new) <= rtol * np.linalg.norm(b):
            return x, k
        p = r + (rr_new / rr) * p  # next direction, A-conjugate to the others
        rr = rr_new
    return x, None

N = 32
T = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(N, N))
A = (sp.kron(sp.identity(N), T) + sp.kron(T, sp.identity(N))).tocsr()
b = np.ones(N * N)
x, iters = conjugate_gradient(A, b)
print("iterations:", iters, " relative residual:", np.linalg.norm(b - A @ x) / np.linalg.norm(b))
iterations: 59  relative residual: 8.340669100656425e-09

Fifty-nine iterations on 1024 unknowns, the same count SciPy's cg reports below. Each step chooses the step length alpha that minimises the AA-norm error along p, then builds the next direction from the new residual so that it is AA-conjugate to every previous one, pi⊤A pj=0\mathbf{p}_i^\top A\,\mathbf{p}_j = 0. That conjugacy is why progress made in earlier directions is never undone, and why only one old direction has to be kept.

Gotcha: in floating point, conjugacy erodes over many iterations, so the finite-termination property does not hold in practice. CG is used as an iterative method with a residual test, never as a direct method that runs nn steps.

6. How fast CG converges

The standard bound, proved in Trefethen and Bau's Lecture 38 by an argument about Chebyshev polynomials, ties CG's speed to the condition number κ\kappa of AA:

∥ek∥A∥e0∥A≤2(κ−1κ+1)k\frac{\|\mathbf{e}_k\|_A}{\|\mathbf{e}_0\|_A} \le 2\left(\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}\right)^{k}

For large κ\kappa the ratio is about 1−2/κ1 - 2/\sqrt{\kappa}, so the iteration count to a fixed tolerance grows like κ\sqrt{\kappa}, against roughly κ\kappa for Jacobi on the model problem. The bound is often pessimistic: clustered eigenvalues make CG faster than it predicts.

Predict first

For the grid Laplacian, the condition number grows about fourfold each time NN doubles: 116, 441, 1712, 6744. Jacobi's iteration count quadruples. What happens to CG's?

7. Measured: Jacobi, CG, and preconditioned CG

The full experiment, SciPy's cg with and without a symmetric SOR preconditioner, against plain Jacobi, on four grid sizes:

import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import cg, spsolve_triangular, LinearOperator

def poisson2d(N):
    """5-point Laplacian on an N x N grid: n = N**2 unknowns, 5 nonzeros per row."""
    T = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(N, N))
    I = sp.identity(N)
    return (sp.kron(I, T) + sp.kron(T, I)).tocsr()

def jacobi(A, b, rtol, maxit=100000):
    D = A.diagonal()
    x = np.zeros_like(b)
    for k in range(maxit):
        r = b - A @ x
        if np.linalg.norm(r) <= rtol * np.linalg.norm(b):
            return k
        x = x + r / D
    return None

def ssor(A, w=1.5):
    """Symmetric SOR preconditioner: SPD whenever A is, so CG accepts it."""
    D = sp.diags(A.diagonal())
    lower = (D / w + sp.tril(A, -1)).tocsr()
    upper = (D / w + sp.triu(A, 1)).tocsr()
    d = A.diagonal() * (2 - w) / w
    apply = lambda r: spsolve_triangular(upper, d * spsolve_triangular(lower, r), lower=False)
    return LinearOperator(A.shape, apply)

def cg_iters(A, b, M=None):
    count = [0]
    x, info = cg(A, b, rtol=1e-8, M=M, callback=lambda xk: count.__setitem__(0, count[0] + 1))
    assert info == 0, info
    return count[0]

for N in (16, 32, 64, 128):
    A = poisson2d(N)
    b = np.ones(N * N)
    kappa = 1 / np.tan(np.pi / (2 * (N + 1))) ** 2      # exact for this matrix
    print(f"N={N:3d}  n={N*N:6d}  cond={kappa:5.0f}  jacobi={jacobi(A, b, 1e-8):5d}  "
          f"cg={cg_iters(A, b)}  cg+ssor={cg_iters(A, b, ssor(A))}")
N= 16  n=   256  cond=  116  jacobi= 1064  cg=28  cg+ssor=15
N= 32  n=  1024  cond=  441  jacobi= 4020  cg=59  cg+ssor=23
N= 64  n=  4096  cond= 1712  jacobi=15599  cg=119  cg+ssor=39
N=128  n= 16384  cond= 6744  jacobi=61430  cg=239  cg+ssor=72

cond is computed from the closed form cot⁡2 ⁣(π/(2(N+1)))\cot^2\!\big(\pi / (2(N+1))\big), exact for this matrix. Reading down the columns: Jacobi multiplies by about 4 per row, CG by about 2, and preconditioned CG by less than 2. The SSOR preconditioner is chosen because it stays symmetric positive definite when AA is, which CG requires; an incomplete LU factor is not symmetric and can make cg fail.

8. Preconditioning: change the problem CG sees

If convergence depends on κ\kappa, reduce κ\kappa. A preconditioner MM approximates AA but is cheap to invert, and the method is run on M−1Ax=M−1bM^{-1}A\mathbf{x} = M^{-1}\mathbf{b}, whose condition number can be far smaller. SciPy's cg documentation describes its M argument as approximating the inverse of AA, chosen so the preconditioned matrix has a smaller condition number.

Iterations to a 1e-8 residual on the N by N grid Laplacian
CGCG with SSOR preconditioner
iterations050100150200250N = 16N = 32N = 64N = 128
Source: Computed with the code in this lesson, SciPy 1.17 scipy.sparse.linalg.cg

The trade is always the same: each iteration costs one extra application of M−1M^{-1}, and the preconditioner must cut iterations by more than that. Common choices, from cheapest to strongest:

PreconditionerIdea
Jacobi (diagonal)Rescale rows; helps when diagonal entries vary widely
SSOROne symmetric Gauss-Seidel sweep each way
Incomplete Cholesky or LUFactor AA but discard most fill-in
MultigridSolve smooth error components on coarser grids

9. Beyond symmetric positive definite

CG's short recurrence and its error minimisation both depend on AA being SPD. For other matrices the Krylov idea survives, but some property has to give.

MethodMatrixMinimisesMemory per iterationSciPy
CGSymmetric positive definiteAA-norm of the errorConstantcg
MINRESSymmetric, possibly indefinite2-norm of the residualConstantminres
GMRESAny nonsingular2-norm of the residualGrows with kkgmres
BiCGSTABAny nonsingularNothing exactlyConstantbicgstab

GMRES (Trefethen and Bau, Lecture 35) is the robust general choice: its residual never increases, but it must store one vector per iteration, so implementations restart after a fixed number of steps, which SciPy exposes as the restart parameter, and a restarted GMRES can stall. BiCGSTAB keeps memory constant at the price of irregular, non-monotone convergence.

In practice: preconditioning matters even more for nonsymmetric problems than for SPD ones. An unpreconditioned GMRES on a hard problem is usually a sign the setup is unfinished, not that the method failed.

10. Tolerances, and checking that it converged

An iterative solver returns whatever it has when it stops, so the stopping rule is part of the answer. SciPy's cg documents its rule as

∥b−Axk∥≤max⁡(rtol⋅∥b∥,  atol)\|\mathbf{b} - A\mathbf{x}_k\| \le \max(\text{rtol}\cdot\|\mathbf{b}\|,\; \text{atol})

with defaults rtol=1e-5 and atol=0.0. Three consequences are easy to miss:

  1. The default is loose. Five digits of residual is fine inside a Newton iteration and too coarse as a final answer. Set rtol deliberately.
  2. Residual is not error. From the previous lesson, the relative error can be up to κ(A)\kappa(A) times the relative residual. On a grid with κ≈7000\kappa \approx 7000, a 10−510^{-5} residual guarantees only about 10−110^{-1} in the worst case, even though typical errors are far smaller.
  3. Non-convergence is not an exception. cg returns an info flag, 0 on success and a positive iteration count when the tolerance was not reached. Code that ignores info silently uses an unconverged answer.

Try it: rerun the experiment above with rtol=1e-5 and compare x to scipy.sparse.linalg.spsolve(A, b). Then shrink the grid spacing and watch how the iteration count and the gap to the direct solution change.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. A splitting iteration has spectral radius 0.999. Roughly how many iterations reduce the error by a factor of 1e-6?
    • About 14,000
    • About 60
    • About 1,400
    • About 6,000,000
  2. On the grid Laplacian, the condition number grows about fourfold when N doubles. How does the CG iteration count change?
    • It stays constant
    • It roughly quadruples
    • It grows by a factor of 16
    • It roughly doubles
  3. Why was an SSOR preconditioner used with CG instead of an incomplete LU factor?
    • Incomplete LU needs more memory than the matrix itself
    • CG requires a symmetric positive definite preconditioner, and incomplete LU is not symmetric
    • SSOR is always the strongest preconditioner
    • SciPy's cg rejects LinearOperator preconditioners
  4. Which method is the robust general choice for a large nonsymmetric sparse system, and what is its main cost?
    • CG, because it needs only constant memory
    • Jacobi, because it never diverges
    • GMRES, whose memory grows with the iteration count, hence restarts
    • MINRES, because it minimises the error in the A-norm
  5. scipy.sparse.linalg.cg returns info = 500. What does that mean?
    • It converged in 500 iterations
    • The matrix has 500 negative eigenvalues
    • The preconditioner failed at row 500
    • The tolerance was not reached, and the answer is unconverged

Related lessons

Math
advanced

Solving Ax = b Directly: LU, Pivoting, and Never Inverting

How a computer actually solves a linear system: Gaussian elimination as an LU factorisation, why you factor once and never invert, how a tiny pivot wrecks a harmless problem, what partial pivoting and the growth factor guarantee, when Cholesky applies, and where fill-in ends the direct approach.

10 steps·~15 min
Math
advanced

Stiff Equations, Stability Regions, and Adaptive Step Size

Why an ODE solver can blow up at step sizes accuracy would never demand. Learn stability regions on the test equation, what makes a problem stiff, how implicit methods and A-stability fix it at the cost of Newton solves, how BDF and Radau escape Dahlquist's barrier, and how adaptive solvers choose each step.

12 steps·~18 min
Math
advanced

Root Finding: Bisection, Newton, and Knowing When to Stop

Most equations have no formula for their solution, so computers chase roots with sequences. Compare bisection, secant, Newton and Brent's method by convergence order and guarantees, watch Newton fail, learn how accurate a root can be, and pick stopping tests that do not lie.

11 steps·~17 min
Math
intermediate

What a Differential Equation Says: Rates, Solutions, and Slope Fields

A differential equation is a local rule for change, not a formula for the answer. Learn to read and classify one, solve the exponential and logistic cases, know when a unique solution exists, turn any order into a first-order system, and step forward numerically with Euler and Runge-Kutta.

10 steps·~15 min