Deriving conjugate gradients from a minimization problem

Environment

Python 3.14.6, NumPy 2.5.4, SciPy 1.18.1, Matplotlib 3.11.2.

This article is a rewrite of a post from around 2013–2016, with calculations performed in the environment described above.

Overview

The conjugate gradient method, CG, iteratively solves linear systems with real symmetric positive definite matrices. Starting from quadratic minimization, we derive line search, conjugate directions, and the update coefficients. Python examples compare it with steepest descent and test sparse systems. Nonlinear conjugate gradients and preconditioning are outside this article’s scope.

Setup

Run the code in Jupyter Notebook from top to bottom.

Imports and plotting setup
import platform
from pathlib import Path
from pprint import pprint

import numpy as np
import scipy
from scipy.sparse import diags
from scipy.sparse.linalg import cg, spsolve
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, MaxNLocator
from IPython.display import Latex, SVG, display

print("Environment: wa-src(3.14.6)")
print(f"Python: {platform.python_version()} / OS: {platform.system()}")
print(f"NumPy: {np.__version__}, SciPy: {scipy.__version__}")
print(f"Matplotlib: {matplotlib.__version__}")

OUT = Path("105_nb_files")
OUT.mkdir(exist_ok=True)

def sig(value):
    return f"{float(value):#.3g}"

np.set_printoptions(formatter={"float_kind": sig})
plt.rcParams.update({"font.size": 11, "svg.fonttype": "none"})

def save_svg(fig, name):
    # Show decimal ticks with three significant digits and iteration counts as integers.
    for ax in fig.axes:
        if ax.get_xlabel() == "Iteration":
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
        elif ax.get_xscale() == "linear":
            ax.xaxis.set_major_formatter(FuncFormatter(lambda v, _: sig(v)))
        if ax.get_yscale() == "linear":
            ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: sig(v)))
    fig.tight_layout()
    path = OUT / name
    fig.savefig(path, format="svg", bbox_inches="tight")
    plt.close(fig)
    display(SVG(filename=str(path)))
Environment: wa-src(3.14.6)
Python: 3.14.6 / OS: Darwin
NumPy: 2.5.4, SciPy: 1.18.1
Matplotlib: 3.11.2

1. Turning a linear system into minimization

Let $\mathbf{A}\in\mathbb{R}^{n\times n}$ and $\mathbf{b},\mathbf{x}\in\mathbb{R}^n$. Assume

$$ \mathbf{A}^{\mathsf T}=\mathbf{A},\qquad \mathbf{v}^{\mathsf T}\mathbf{A}\mathbf{v}\gt 0 \quad(\mathbf{v}\ne\mathbf{0}) $$

Consider the following quadratic function.

$$ f(\mathbf{x})=\frac12\mathbf{x}^{\mathsf T}\mathbf{A}\mathbf{x} -\mathbf{b}^{\mathsf T}\mathbf{x} =\frac12\sum_{i=1}^n\sum_{j=1}^n A_{ij}x_ix_j-\sum_{i=1}^n b_ix_i. $$

Differentiate with respect to component $x_\ell$. Symmetry makes the two sums equal.

$$ \begin{aligned} \frac{\partial f}{\partial x_\ell} &=\frac12\sum_j A_{\ell j}x_j+\frac12\sum_i A_{i\ell}x_i-b_\ell\\ &=\sum_j A_{\ell j}x_j-b_\ell,\\ \nabla f(\mathbf{x})&=\mathbf{A}\mathbf{x}-\mathbf{b},\qquad \nabla^2 f(\mathbf{x})=\mathbf{A}. \end{aligned} $$

The Hessian is positive definite, so $f$ is strictly convex. The stationary condition $\nabla f(\mathbf{x}_*)=\mathbf{0}$ becomes $\mathbf{A}\mathbf{x}_*=\mathbf{b}$, whose solution is the unique minimizer. Substituting the error $\mathbf{e}=\mathbf{x}-\mathbf{x}_*$ confirms this.

$$ \begin{aligned} f(\mathbf{x}_*+\mathbf{e})-f(\mathbf{x}_*) &=\frac12\mathbf{x}_*^{\mathsf T}\mathbf{A}\mathbf{e} +\frac12\mathbf{e}^{\mathsf T}\mathbf{A}\mathbf{x}_* +\frac12\mathbf{e}^{\mathsf T}\mathbf{A}\mathbf{e}-\mathbf{b}^{\mathsf T}\mathbf{e}\\ &=\mathbf{e}^{\mathsf T}(\mathbf{A}\mathbf{x}_*-\mathbf{b}) +\frac12\mathbf{e}^{\mathsf T}\mathbf{A}\mathbf{e}\\ &=\frac12\mathbf{e}^{\mathsf T}\mathbf{A}\mathbf{e} =\frac12\|\mathbf{e}\|_{\mathbf{A}}^2\ge0. \end{aligned} $$

Here $\|\mathbf{e}\|_{\mathbf{A}}=\sqrt{\mathbf{e}^{\mathsf T}\mathbf{A}\mathbf{e}}$. Write the residual as $\mathbf{r}_k=\mathbf{b}-\mathbf{A}\mathbf{x}_k=-\nabla f(\mathbf{x}_k)$. Since it is the negative gradient, it can serve as the steepest descent direction.

2. Minimizing along a line

Move along a nonzero direction $\mathbf{p}_k$ by $\mathbf{x}_{k+1}=\mathbf{x}_k+\alpha_k\mathbf{p}_k$. Expanding $\phi(\alpha)=f(\mathbf{x}_k+\alpha\mathbf{p}_k)$ gives

$$ \begin{aligned} \phi(\alpha) &=\frac12\mathbf{x}_k^{\mathsf T}\mathbf{A}\mathbf{x}_k +\frac\alpha2(\mathbf{x}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k +\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{x}_k) +\frac{\alpha^2}{2}\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k -\mathbf{b}^{\mathsf T}\mathbf{x}_k-\alpha\mathbf{b}^{\mathsf T}\mathbf{p}_k\\ &=f(\mathbf{x}_k)-\alpha\mathbf{r}_k^{\mathsf T}\mathbf{p}_k +\frac{\alpha^2}{2}\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k,\\ \phi^{\prime}(\alpha)&=-\mathbf{r}_k^{\mathsf T}\mathbf{p}_k +\alpha\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k. \end{aligned} $$

The second derivative is positive, so $\phi^{\prime}(\alpha_k)=0$ gives

$$ \alpha_k=\frac{\mathbf{r}_k^{\mathsf T}\mathbf{p}_k} {\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k},\qquad \mathbf{r}_{k+1}=\mathbf{r}_k-\alpha_k\mathbf{A}\mathbf{p}_k $$

Consequently, $\mathbf{p}_k^{\mathsf T}\mathbf{r}_{k+1}=\mathbf{p}_k^{\mathsf T}\mathbf{r}_k-\alpha_k\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k=0$.

Choosing $\mathbf{p}_k=\mathbf{r}_k$ every time gives steepest descent, with $\alpha_k=\mathbf{r}_k^{\mathsf T}\mathbf{r}_k/(\mathbf{r}_k^{\mathsf T}\mathbf{A}\mathbf{r}_k)$. The next figure shows two-dimensional contours and the first line search.

A = np.array([[4, 1], [1, 3]], dtype=float)
b = np.array([1, 2], dtype=float)
x_star = np.linalg.solve(A, b)

def objective(x):
    return x @ A @ x / 2 - b @ x

u, v = np.meshgrid(np.linspace(-1, 1, 180), np.linspace(-1, 2, 180))
F = (4 * u**2 + 2 * u * v + 3 * v**2) / 2 - u - 2 * v
alpha = np.linspace(0, 1 / 2, 150)
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].contour(u, v, F, levels=12, cmap="viridis")
axes[0].plot(*x_star, "r*", ms=12, label="Minimum")
axes[0].plot([0, 1 / 4], [0, 1 / 2], "o-", label="First step")
axes[0].set(xlabel="$x_1$", ylabel="$x_2$", title="Quadratic objective")
axes[0].set_xticks([-1, -1 / 2, 0, 1 / 2, 1])
axes[0].legend()
axes[1].plot(alpha, [objective(t * b) for t in alpha])
axes[1].axvline(1 / 4, ls="--", color="tab:red", label=r"$\alpha_0=1/4$")
axes[1].set(xlabel=r"$\alpha$", ylabel=r"$f(\alpha\mathbf{b})$", title="Exact line search")
axes[1].legend()
save_svg(fig, "01_objective.svg")

3. Directions that preserve earlier minimization

In steepest descent, later updates can undo the stationary conditions along earlier directions. To prevent this, impose the following condition on distinct directions.

$$ \mathbf{p}_i^{\mathsf T}\mathbf{A}\mathbf{p}_j=0\quad(i\ne j) $$

This is $\mathbf{A}$-conjugacy. It differs from ordinary orthogonality, $\mathbf{p}_i^{\mathsf T}\mathbf{p}_j=0$.

Let $S_k=\operatorname{span}\{\mathbf{p}_0,\ldots,\mathbf{p}_{k-1}\}$. If $\mathbf{x}_k$ minimizes $f$ on $\mathbf{x}_0+S_k$, every directional derivative there is zero, giving $\mathbf{p}_i^{\mathsf T}\mathbf{r}_k=0$ for $i\lt k$. If the new direction is conjugate to the earlier ones, then

$$ \mathbf{p}_i^{\mathsf T}\mathbf{r}_{k+1} =\mathbf{p}_i^{\mathsf T}\mathbf{r}_k -\alpha_k\mathbf{p}_i^{\mathsf T}\mathbf{A}\mathbf{p}_k=0\quad(i\lt k). $$

Line search makes the same expression zero for $i=k$. Thus $\mathbf{x}_{k+1}$ minimizes $f$ on the expanded space $\mathbf{x}_0+S_{k+1}$.

4. Building conjugate directions from residuals

Start with $\mathbf{p}_0=\mathbf{r}_0$ and consider the form

$$ \mathbf{p}_{k+1}=\mathbf{r}_{k+1}+\beta_k\mathbf{p}_k $$

The following derivation assumes exact arithmetic and a residual that has not yet become zero.

The numerator of the step length

The recurrence shows that the residuals and directions span the same space. Indeed, $\mathbf{r}_k=\mathbf{p}_k-\beta_{k-1}\mathbf{p}_{k-1}$, while the reverse recurrence expresses $\mathbf{p}_k$ using earlier residuals. The previous section’s orthogonality condition gives, for $k\ge1$,

$$ \mathbf{r}_k^{\mathsf T}\mathbf{p}_k =\mathbf{r}_k^{\mathsf T}(\mathbf{r}_k+\beta_{k-1}\mathbf{p}_{k-1}) =\mathbf{r}_k^{\mathsf T}\mathbf{r}_k. $$

The same holds for $k=0$. Thus $\alpha_k=\mathbf{r}_k^{\mathsf T}\mathbf{r}_k/(\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k)$. Since $\mathbf{r}_{k+1}$ is orthogonal to $S_{k+1}$, it is also orthogonal to $\mathbf{r}_0,\ldots,\mathbf{r}_k$ in that space.

Deriving $\beta_k$

Apply the conjugacy condition with the preceding direction.

$$ \begin{aligned} 0&=\mathbf{p}_{k+1}^{\mathsf T}\mathbf{A}\mathbf{p}_k =\mathbf{r}_{k+1}^{\mathsf T}\mathbf{A}\mathbf{p}_k +\beta_k\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k,\\ \beta_k&=-\frac{\mathbf{r}_{k+1}^{\mathsf T}\mathbf{A}\mathbf{p}_k} {\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k}. \end{aligned} $$

Rearrange the residual update as $\mathbf{A}\mathbf{p}_k=(\mathbf{r}_k-\mathbf{r}_{k+1})/\alpha_k$ to obtain

$$ \begin{aligned} \mathbf{r}_{k+1}^{\mathsf T}\mathbf{A}\mathbf{p}_k &=\frac{\mathbf{r}_{k+1}^{\mathsf T}\mathbf{r}_k- \mathbf{r}_{k+1}^{\mathsf T}\mathbf{r}_{k+1}}{\alpha_k} =-\frac{\mathbf{r}_{k+1}^{\mathsf T}\mathbf{r}_{k+1}}{\alpha_k},\\ \beta_k&=\frac{\mathbf{r}_{k+1}^{\mathsf T}\mathbf{r}_{k+1}} {\alpha_k\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k} =\frac{\mathbf{r}_{k+1}^{\mathsf T}\mathbf{r}_{k+1}} {\mathbf{r}_k^{\mathsf T}\mathbf{r}_k}. \end{aligned} $$

Conjugacy is required with directions $j\lt k$ too, not just the preceding one. Earlier conjugacy and residual orthogonality give

$$ \begin{aligned} \mathbf{p}_{k+1}^{\mathsf T}\mathbf{A}\mathbf{p}_j &=\mathbf{r}_{k+1}^{\mathsf T}\mathbf{A}\mathbf{p}_j +\beta_k\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_j\\ &=\frac{\mathbf{r}_{k+1}^{\mathsf T}\mathbf{r}_j -\mathbf{r}_{k+1}^{\mathsf T}\mathbf{r}_{j+1}}{\alpha_j}+0=0. \end{aligned} $$

Starting with $\mathbf{p}_0=\mathbf{r}_0$, minimization, residual orthogonality, and conjugacy of each new direction are preserved by induction. The update equations are collected below.

# Display the main equations as LaTeX in the output area.
display(Latex(r"\(\displaystyle \begin{aligned}"
    r"\alpha_k&=\frac{\mathbf{r}_k^{\mathsf T}\mathbf{r}_k}"
    r"{\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k},\\"
    r"\mathbf{x}_{k+1}&=\mathbf{x}_k+\alpha_k\mathbf{p}_k,\\"
    r"\mathbf{r}_{k+1}&=\mathbf{r}_k-\alpha_k\mathbf{A}\mathbf{p}_k,\\"
    r"\beta_k&=\frac{\mathbf{r}_{k+1}^{\mathsf T}\mathbf{r}_{k+1}}"
    r"{\mathbf{r}_k^{\mathsf T}\mathbf{r}_k},\\"
    r"\mathbf{p}_{k+1}&=\mathbf{r}_{k+1}+\beta_k\mathbf{p}_k"
    r"\end{aligned}\)"))

$$ \displaystyle \begin{aligned}\alpha_k&=\frac{\mathbf{r}_k^{\mathsf T}\mathbf{r}_k}{\mathbf{p}_k^{\mathsf T}\mathbf{A}\mathbf{p}_k},\\\mathbf{x}_{k+1}&=\mathbf{x}_k+\alpha_k\mathbf{p}_k,\\\mathbf{r}_{k+1}&=\mathbf{r}_k-\alpha_k\mathbf{A}\mathbf{p}_k,\\\beta_k&=\frac{\mathbf{r}_{k+1}^{\mathsf T}\mathbf{r}_{k+1}}{\mathbf{r}_k^{\mathsf T}\mathbf{r}_k},\\\mathbf{p}_{k+1}&=\mathbf{r}_{k+1}+\beta_k\mathbf{p}_k\end{aligned} $$

Nonzero conjugate directions are linearly independent. Multiply $\sum_i c_i\mathbf{p}_i=\mathbf{0}$ by $\mathbf{p}_j^{\mathsf T}\mathbf{A}$ to obtain $c_j\mathbf{p}_j^{\mathsf T}\mathbf{A}\mathbf{p}_j=0$. Positive definiteness gives $c_j=0$. Thus exact arithmetic reaches the solution in at most $n$ iterations.

Until convergence, the generated space is

$$ S_k=\mathcal{K}_k(\mathbf{A},\mathbf{r}_0) =\operatorname{span}\{\mathbf{r}_0,\mathbf{A}\mathbf{r}_0, \ldots,\mathbf{A}^{k-1}\mathbf{r}_0\} $$

Tracing the matrix products in the recurrence establishes inclusion, and the $k$ independent directions give equal dimensions. On this space, CG minimizes $f$, or equivalently the $\mathbf{A}$-norm of the error. It does not minimize the Euclidean residual norm $\|\mathbf{r}_k\|_2$, which may increase during iteration.

5. A two-dimensional example by hand

Use the matrix from the first figure and set $\mathbf{x}_0=\mathbf{0}$.

$$ \mathbf{A}=\begin{pmatrix}4&1\\1&3\end{pmatrix},\quad \mathbf{b}=\begin{pmatrix}1\\2\end{pmatrix},\quad \mathbf{p}_0=\mathbf{r}_0=\mathbf{b}. $$

This matrix is positive definite because $A_{11}=4\gt 0$ and $\det\mathbf{A}=11\gt 0$. The first update is

$$ \begin{aligned} \mathbf{A}\mathbf{p}_0&=\begin{pmatrix}6\\7\end{pmatrix},& \alpha_0&=\frac{1^2+2^2}{1\cdot6+2\cdot7}=\frac14,\\ \mathbf{x}_1&=\frac14\begin{pmatrix}1\\2\end{pmatrix},& \mathbf{r}_1&=\begin{pmatrix}1\\2\end{pmatrix} -\frac14\begin{pmatrix}6\\7\end{pmatrix} =\begin{pmatrix}-1/2\\1/4\end{pmatrix}. \end{aligned} $$

The next direction and step length are

$$ \begin{aligned} \beta_0&=\frac{1/4+1/16}{5}=\frac1{16},\\ \mathbf{p}_1&=\begin{pmatrix}-1/2\\1/4\end{pmatrix} +\frac1{16}\begin{pmatrix}1\\2\end{pmatrix} =\frac1{16}\begin{pmatrix}-7\\6\end{pmatrix},\\ \mathbf{A}\mathbf{p}_1&=\frac1{16}\begin{pmatrix}-22\\11\end{pmatrix},\\ \alpha_1&=\frac{5/16}{(154+66)/256}=\frac{5/16}{55/64}=\frac4{11},\\ \mathbf{x}_2&=\begin{pmatrix}1/4\\1/2\end{pmatrix} +\frac4{11}\frac1{16}\begin{pmatrix}-7\\6\end{pmatrix} =\begin{pmatrix}1/11\\7/11\end{pmatrix}. \end{aligned} $$

We obtain $\mathbf{A}\mathbf{x}_2=(1,2)^{\mathsf T}=\mathbf{b}$. Also, $\mathbf{r}_0^{\mathsf T}\mathbf{r}_1=-1/2+2/4=0$ and $\mathbf{p}_0^{\mathsf T}\mathbf{A}\mathbf{p}_1=(-22+22)/16=0$.

6. Implementing the updates in Python

The following function assumes a real symmetric positive definite matrix and accepts both dense arrays and sparse matrices. Setting use_cg=False resets the direction to the residual, giving steepest descent. If the initial point is already a solution, it stops before division. Saving the history for study costs an extra $O(kn)$ memory for $k$ iterations. CG without this history needs only $O(n)$ additional memory, excluding matrix storage.

def solve_quadratic(A, b, x0=None, *, use_cg=True,
                    rtol=1.00e-10, atol=0.00, maxiter=1000):
    """Run CG or steepest descent and return the solution, history, and convergence flag."""
    x = np.zeros_like(b, dtype=float) if x0 is None else np.array(x0, dtype=float)
    r = b - A @ x
    p = r.copy()
    xs, rs, ps = [x.copy()], [r.copy()], []
    threshold = max(atol, rtol * np.linalg.norm(b))
    rr = r @ r

    for _ in range(maxiter):
        if np.sqrt(rr) <= threshold:
            break
        Ap = A @ p
        curvature = p @ Ap
        if curvature <= 0:
            raise ValueError("Curvature along the search direction is not positive")
        ps.append(p.copy())
        alpha = rr / curvature
        x = x + alpha * p
        r = r - alpha * Ap
        rr_new = r @ r
        beta = rr_new / rr if use_cg else 0
        p = r + beta * p
        rr = rr_new
        xs.append(x.copy())
        rs.append(r.copy())

    # Recompute the final residual because rounding can separate recursive and true residuals.
    converged = np.linalg.norm(b - A @ x) <= threshold
    history = {"x": np.array(xs), "r": np.array(rs), "p": np.array(ps)}
    return x, history, bool(converged)

x, small, ok = solve_quadratic(A, b)
pprint({"solution": x, "iterations": len(small["p"]), "converged": ok,
        "true residual norm": sig(np.linalg.norm(b - A @ x))})
assert ok and np.allclose(x, [1 / 11, 7 / 11], rtol=1.00e-12, atol=1.00e-14)
{'converged': True,
 'iterations': 2,
 'solution': array([0.0909, 0.636]),
 'true residual norm': '0.00'}

Comparing paths and convergence

To make the difference visible, use $\mathbf{A}=\begin{pmatrix}10&9\\9&10\end{pmatrix}$, $\mathbf{b}=(1,2)^{\mathsf T}$, and $\mathbf{x}_0=(-2,2)^{\mathsf T}$. The eigenvalues are $1,19$. The path plot shows only the first 18 steepest descent iterations; the convergence plot shows all iterations. SD stands for steepest descent.

A_path = np.array([[10, 9], [9, 10]], dtype=float)
x0 = np.array([-2, 2], dtype=float)
reference = np.linalg.solve(A_path, b)
runs = {}
for label, use_cg in [("SD", False), ("CG", True)]:
    _, h, success = solve_quadratic(A_path, b, x0, use_cg=use_cg)
    runs[label] = h
    pprint({"method": label, "iterations": len(h["p"]), "converged": success})

u, v = np.meshgrid(np.linspace(-2.2, 0, 180), np.linspace(0, 2.2, 180))
e1, e2 = u - reference[0], v - reference[1]
gap = (10 * e1**2 + 18 * e1 * e2 + 10 * e2**2) / 2
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, (label, h) in zip(axes, runs.items()):
    path = h["x"][:19]
    ax.contour(u, v, gap, levels=np.geomspace(1.00e-2, 20, 13), colors="0.75")
    ax.plot(path[:, 0], path[:, 1], "o-", ms=4, label=label)
    ax.plot(*reference, "r*", ms=12, label="Solution")
    ax.set(xlabel="$x_1$", ylabel="$x_2$", title=label, aspect="equal")
    ax.legend()
save_svg(fig, "02_paths.svg")
{'converged': True, 'iterations': 222, 'method': 'SD'}
{'converged': True, 'iterations': 2, 'method': 'CG'}
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for label, h in runs.items():
    errors = h["x"] - reference
    # Avoid cancellation when subtracting f(x)-f(x*).
    energy = np.einsum("ki,ij,kj->k", errors, A_path, errors) / 2
    residual = np.linalg.norm(b - h["x"] @ A_path.T, axis=1) / np.linalg.norm(b)
    axes[0].semilogy(np.maximum(energy, 1.00e-16), ".-", label=label)
    axes[1].semilogy(np.maximum(residual, 1.00e-16), ".-", label=label)
for ax, title in zip(axes, ["Objective gap", "True relative residual"]):
    ax.set(xlabel="Iteration", ylabel=title, title=title)
    ax.grid(alpha=0.300)
    ax.legend()
save_svg(fig, "03_convergence.svg")

Compute the objective gap from $\frac12(\mathbf{x}_k-\mathbf{x}_*)^{\mathsf T}\mathbf{A}(\mathbf{x}_k-\mathbf{x}_*)$. To represent zero on logarithmic plots, clip values below $10^{-16}$ to $10^{-16}$ for display only. CG reaches the solution in two iterations, while steepest descent repeatedly changes direction.

Checking orthogonality and conjugacy numerically

Also test a six-dimensional diagonal matrix. The heatmaps show absolute normalized inner products: $|\mathbf{r}_i^{\mathsf T}\mathbf{r}_j|/(\|\mathbf{r}_i\|_2\|\mathbf{r}_j\|_2)$ for residuals and $|\mathbf{p}_i^{\mathsf T}\mathbf{A}\mathbf{p}_j|/(\|\mathbf{p}_i\|_{\mathbf{A}}\|\mathbf{p}_j\|_{\mathbf{A}})$ for directions. Exclude the nearly zero residual after convergence from normalization.

A_check = np.diag(np.arange(1, 7, dtype=float))
b_check = np.random.default_rng(105).normal(size=6)
_, h, ok = solve_quadratic(A_check, b_check, rtol=1.00e-12)
R, P = h["r"][:-1], h["p"]

def normalize_gram(G):
    scale = np.sqrt(np.diag(G))
    return G / np.outer(scale, scale)

grams = [normalize_gram(R @ R.T), normalize_gram(P @ A_check @ P.T)]
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, G, title in zip(axes, grams, ["Residual orthogonality", "A-conjugate directions"]):
    im = ax.imshow(np.abs(G), vmin=0, vmax=1, cmap="Blues")
    ax.set(title=title, xlabel="$j$", ylabel="$i$")
    ax.set_xticks(range(len(G)))
    ax.set_yticks(range(len(G)))
    fig.colorbar(im, ax=ax)
save_svg(fig, "04_orthogonality.svg")
pprint({"maximum absolute off-diagonal entries": [sig(np.max(np.abs(G - np.eye(len(G)))))
                                      for G in grams]})
assert ok and all(np.max(np.abs(G - np.eye(len(G)))) < 1.00e-10 for G in grams)
{'maximum absolute off-diagonal entries': ['5.46e-14', '5.78e-14']}

Varying the condition number

For a symmetric positive definite matrix, $\kappa_2(\mathbf{A})=\lambda_{\max}/\lambda_{\min}$. The next experiment spaces eigenvalues evenly from $1$ to $\kappa$ and uses the same right-hand side. Larger condition numbers often slow convergence, but the iteration count also depends on the eigenvalue distribution and right-hand side. Floating-point arithmetic can lose orthogonality, so the bound of at most $n$ iterations no longer holds directly.

n = 60
rhs = np.random.default_rng(105).normal(size=n)
fig, ax = plt.subplots(figsize=(7, 4))
for kappa in [10, 100, 1000]:
    spectrum = np.linspace(1, kappa, n)
    D = diags(spectrum, format="csr")
    _, h, ok = solve_quadratic(D, rhs)
    residual = np.linalg.norm(rhs - h["x"] * spectrum, axis=1) / np.linalg.norm(rhs)
    ax.semilogy(np.maximum(residual, 1.00e-16), label=fr"$\kappa={kappa}$")
    pprint({"condition number": kappa, "iterations": len(h["p"]), "converged": ok})
ax.set(xlabel="Iteration", ylabel="True relative residual", title="Different spectra")
ax.grid(alpha=0.300)
ax.legend()
save_svg(fig, "05_condition_number.svg")
{'condition number': 10, 'converged': True, 'iterations': 32}
{'condition number': 100, 'converged': True, 'iterations': 47}
{'condition number': 1000, 'converged': True, 'iterations': 51}

7. Checking sparse-system solutions against SciPy

Use a tridiagonal matrix with diagonal entries $2$ and adjacent entries $-1$. It satisfies

$$ \mathbf{v}^{\mathsf T}\mathbf{A}\mathbf{v} =2\sum_{i=1}^n v_i^2-2\sum_{i=1}^{n-1}v_iv_{i+1} =v_1^2+\sum_{i=1}^{n-1}(v_{i+1}-v_i)^2+v_n^2\gt 0 \quad(\mathbf{v}\ne\mathbf{0}) $$

and is therefore positive definite. CG mainly uses matrix–vector products and does not form an inverse. If the number of nonzero entries is $\operatorname{nnz}(\mathbf{A})$, each iteration costs $O(\operatorname{nnz}(\mathbf{A})+n)$.

SciPy’s cg uses the stopping criterion $\|\mathbf{b}-\mathbf{A}\mathbf{x}\|_2\le\max(\mathrm{rtol}\|\mathbf{b}\|_2,\mathrm{atol})$, and info=0 indicates convergence. Recompute the true residual below. Since relative residual and relative solution error differ, also compare with the direct spsolve solution.

n = 120
A_sparse = diags([-np.ones(n - 1), 2 * np.ones(n), -np.ones(n - 1)],
                 offsets=[-1, 0, 1], format="csr")
rhs = np.random.default_rng(105).normal(size=n)
rtol = 1.00e-10
solution, h, ok = solve_quadratic(A_sparse, rhs, rtol=rtol)
norm_b = np.linalg.norm(rhs)
scipy_residuals = [1]

def record_residual(xk):
    scipy_residuals.append(np.linalg.norm(rhs - A_sparse @ xk) / norm_b)

scipy_solution, info = cg(A_sparse, rhs, rtol=rtol, atol=0.00,
                         maxiter=1000, callback=record_residual)
direct = spsolve(A_sparse, rhs)
true_residuals = np.linalg.norm(rhs[:, None] - A_sparse @ h["x"].T, axis=0) / norm_b
relative_error = np.linalg.norm(solution - direct) / np.linalg.norm(direct)
pprint({"custom CG iterations": len(h["p"]), "custom CG converged": ok,
        "SciPy info": info, "SciPy iterations": len(scipy_residuals) - 1,
        "true relative residual": sig(true_residuals[-1]),
        "relative error against the direct solve": sig(relative_error)})

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].plot(direct, label="Direct", lw=3, color="0.7")
axes[0].plot(solution, "--", label="CG")
axes[0].set(xlabel="Index", ylabel="Solution", title="Sparse system solution")
axes[1].semilogy(np.maximum(true_residuals, 1.00e-16), label="Our CG", lw=3)
axes[1].semilogy(np.maximum(scipy_residuals, 1.00e-16), "--", label="SciPy CG")
axes[1].axhline(rtol, color="0.5", ls=":", label="Tolerance")
axes[1].set(xlabel="Iteration", ylabel="True relative residual", title="Convergence")
for ax in axes:
    ax.legend()
    ax.grid(alpha=0.300)
save_svg(fig, "06_sparse_system.svg")

# Check the stopping criterion, agreement with another solver, and zero initial residual.
assert ok and info == 0 and true_residuals[-1] <= rtol
assert np.linalg.norm(rhs - A_sparse @ scipy_solution) / norm_b <= rtol
assert relative_error < 1.00e-9
assert np.allclose(solution, scipy_solution, rtol=1.00e-9, atol=1.00e-10)
_, zero_history, zero_ok = solve_quadratic(A, np.zeros(2))
assert zero_ok and len(zero_history["p"]) == 0
print("Checked stopping conditions, solution agreement, and zero residual.")
{'SciPy info': 0,
 'SciPy iterations': 120,
 'custom CG converged': True,
 'custom CG iterations': 120,
 'relative error against the direct solve': '9.70e-15',
 'true relative residual': '1.02e-13'}
Checked stopping conditions, solution agreement, and zero residual.

Conclusion

We derived conjugate gradient updates by minimizing a positive definite quadratic, then checked paths, orthogonality, and convergence in Python.

Line search chooses the step length, and conjugacy preserves stationary conditions along earlier directions. Together, these give residual orthogonality and the formula for $\beta_k$. Exact arithmetic finishes in at most $n$ iterations; an implementation still needs tolerances, a maximum iteration count, and a check of the true residual.