Hubbry Logo
Conjugate gradient methodConjugate gradient methodMain
Open search
Conjugate gradient method
Community hub
Conjugate gradient method
logo
8 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Conjugate gradient method
Conjugate gradient method
from Wikipedia
A comparison of the convergence of gradient descent with optimal step size (in green) and conjugate vector (in red) for minimizing a quadratic function associated with a given linear system. Conjugate gradient, assuming exact arithmetic, converges in at most n steps, where n is the size of the matrix of the system (here n = 2).

In mathematics, the conjugate gradient method is an algorithm for the numerical solution of particular systems of linear equations, namely those whose matrix is positive-semidefinite. The conjugate gradient method is often implemented as an iterative algorithm, applicable to sparse systems that are too large to be handled by a direct implementation or other direct methods such as the Cholesky decomposition. Large sparse systems often arise when numerically solving partial differential equations or optimization problems.

The conjugate gradient method can also be used to solve unconstrained optimization problems such as energy minimization. It is commonly attributed to Magnus Hestenes and Eduard Stiefel,[1][2] who programmed it on the Z4,[3] and extensively researched it.[4][5]

The biconjugate gradient method provides a generalization to non-symmetric matrices. Various nonlinear conjugate gradient methods seek minima of nonlinear optimization problems.

Description of the problem addressed by conjugate gradients

[edit]

Suppose we want to solve the system of linear equations

for the vector , where the known matrix is symmetric (i.e., ), positive-definite (i.e. for all non-zero vectors in ), and real, and is known as well. We denote the unique solution of this system by .

Derivation as a direct method

[edit]

The conjugate gradient method can be derived from several different perspectives, including specialization of the conjugate direction method for optimization, and variation of the Arnoldi/Lanczos iteration for eigenvalue problems. Despite differences in their approaches, these derivations share a common topic—proving the orthogonality of the residuals and conjugacy of the search directions. These two properties are crucial to developing the well-known succinct formulation of the method.

We say that two non-zero vectors and are conjugate (with respect to ) if

Since is symmetric and positive-definite, the left-hand side defines an inner product

Two vectors are conjugate if and only if they are orthogonal with respect to this inner product. Being conjugate is a symmetric relation: if is conjugate to , then is conjugate to . Suppose that

is a set of mutually conjugate vectors with respect to , i.e. for all . Then forms a basis for , and we may express the solution of in this basis:

Left-multiplying the problem with the vector yields

and so

This gives the following method[4] for solving the equation : find a sequence of conjugate directions, and then compute the coefficients .

As an iterative method

[edit]

If we choose the conjugate vectors carefully, then we may not need all of them to obtain a good approximation to the solution . So, we want to regard the conjugate gradient method as an iterative method. This also allows us to approximately solve systems where is so large that the direct method would take too much time.

We denote the initial guess for by (we can assume without loss of generality that , otherwise consider the system instead). Starting with we search for the solution and in each iteration we need a metric to tell us whether we are closer to the solution (that is unknown to us). This metric comes from the fact that the solution is also the unique minimizer of the following quadratic function

The existence of a unique minimizer is apparent as its Hessian matrix of second derivatives is symmetric positive-definite

and that the minimizer (use ) solves the initial problem follows from its first derivative

This suggests taking the first basis vector to be the negative of the gradient of at . The gradient of equals . Starting with an initial guess , this means we take . The other vectors in the basis will be conjugate to the gradient, hence the name conjugate gradient method. Note that is also the residual provided by this initial step of the algorithm.

Let be the residual at the th step:

As observed above, is the negative gradient of at , so the gradient descent method would require to move in the direction rk. Here, however, we insist that the directions must be conjugate to each other. A practical way to enforce this is by requiring that the next search direction be built out of the current residual and all previous search directions. The conjugation constraint is an orthonormal-type constraint and hence the algorithm can be viewed as an example of Gram-Schmidt orthonormalization. This gives the following expression:

(see the picture at the top of the article for the effect of the conjugacy constraint on convergence). Following this direction, the next optimal location is given by

with

where the last equality follows from the definition of . The expression for can be derived if one substitutes the expression for xk+1 into f and minimizing it with respect to

The resulting algorithm

[edit]

The above algorithm gives the most straightforward explanation of the conjugate gradient method. Seemingly, the algorithm as stated requires storage of all previous searching directions and residue vectors, as well as many matrix–vector multiplications, and thus can be computationally expensive. However, a closer analysis of the algorithm shows that is orthogonal to , i.e. , for . And is -orthogonal to , i.e. , for . This can be regarded that as the algorithm progresses, and span the same Krylov subspace, where form the orthogonal basis with respect to the standard inner product, and form the orthogonal basis with respect to the inner product induced by . Therefore, can be regarded as the projection of on the Krylov subspace.

That is, if the CG method starts with , then[6]The algorithm is detailed below for solving where is a real, symmetric, positive-definite matrix. The input vector can be an approximate initial solution or . It is a different formulation of the exact procedure described above.

This is the most commonly used algorithm. The same formula for is also used in the Fletcher–Reeves nonlinear conjugate gradient method.

Restarts

[edit]

We note that is computed by the gradient descent method applied to . Setting would similarly make computed by the gradient descent method from , i.e., can be used as a simple implementation of a restart of the conjugate gradient iterations.[4] Restarts could slow down convergence, but may improve stability if the conjugate gradient method misbehaves, e.g., due to round-off error.

Explicit residual calculation

[edit]

The formulas and , which both hold in exact arithmetic, make the formulas and mathematically equivalent. The former is used in the algorithm to avoid an extra multiplication by since the vector is already computed to evaluate . The latter may be more accurate, substituting the explicit calculation for the implicit one by the recursion subject to round-off error accumulation, and is thus recommended for an occasional evaluation.[7]

A norm of the residual is typically used for stopping criteria. The norm of the explicit residual provides a guaranteed level of accuracy both in exact arithmetic and in the presence of the rounding errors, where convergence naturally stagnates. In contrast, the implicit residual is known to keep getting smaller in amplitude well below the level of rounding errors and thus cannot be used to determine the stagnation of convergence.

Computation of alpha and beta

[edit]

In the algorithm, is chosen such that is orthogonal to . The denominator is simplified from

since . The is chosen such that is conjugate to . Initially, is

using

and equivalently

the numerator of is rewritten as

because and are orthogonal by design. The denominator is rewritten as

using that the search directions are conjugated and again that the residuals are orthogonal. This gives the in the algorithm after cancelling .

using LinearAlgebra

"""
    x = conjugate_gradient(A, b, x0 = zero(b); atol=length(b)*eps(norm(b))

Return the solution to `A * x = b` using the conjugate gradient method.
`A` must be a positive definite matrix or other linear operator.
`x0` is the initial guess for the solution (default is the zero vector).
`atol` is the absolute tolerance on the magnitude of the residual `b - A * x`
for convergence (default is machine epsilon).

Returns the approximate solution vector `x`.
"""
function conjugate_gradient(
    A, b::AbstractVector, x0::AbstractVector = zero(b); atol=length(b)*eps(norm(b))
)
    x = copy(x0)                        # initialize the solution
    r = b - A * x0                      # initial residual
    p = copy(r)                         # initial search direction
    r²old = r' * r                      # squared norm of residual

    k = 0
    while r²old > atol^2                # iterate until convergence
        Ap = A * p                      # search direction
        α = r²old / (p' * Ap)           # step size
        @. x += α * p                   # update solution
        # Update residual:
        if (k + 1) % 16 == 0            # every 16 iterations, recompute residual from scratch 
            r .= b .- A * x             # to avoid accumulation of numerical errors
        else
            @. r -= α * Ap              # use the updating formula that saves one matrix-vector product
        end
        r²new = r' * r
        @. p = r + (r²new / r²old) * p  # update search direction
        r²old = r²new                   # update squared residual norm
        k += 1
    end

    return x
end

Example code in MATLAB

[edit]
function x = conjugate_gradient(A, b, x0, tol)
% Return the solution to `A * x = b` using the conjugate gradient method.
% Reminder: A should be symmetric and positive definite.

    if nargin < 4
        tol = eps;
    end

    r = b - A * x0;
    p = r;
    rsold = r' * r;

    x = x0;

    while sqrt(rsold) > tol
        Ap = A * p;
        alpha = rsold / (p' * Ap);
        x = x + alpha * p;
        r = r - alpha * Ap;
        rsnew = r' * r;
        p = r + (rsnew / rsold) * p;
        rsold = rsnew;
    end
end


Numerical example

[edit]

Consider the linear system Ax = b given by

we will perform two steps of the conjugate gradient method beginning with the initial guess

in order to find an approximate solution to the system.

Solution

[edit]

For reference, the exact solution is

Our first step is to calculate the residual vector r0 associated with x0. This residual is computed from the formula r0 = b - Ax0, and in our case is equal to

Since this is the first iteration, we will use the residual vector r0 as our initial search direction p0; the method of selecting pk will change in further iterations.

We now compute the scalar α0 using the relationship

We can now compute x1 using the formula

This result completes the first iteration, the result being an "improved" approximate solution to the system, x1. We may now move on and compute the next residual vector r1 using the formula

Our next step in the process is to compute the scalar β0 that will eventually be used to determine the next search direction p1.

Now, using this scalar β0, we can compute the next search direction p1 using the relationship

We now compute the scalar α1 using our newly acquired p1 using the same method as that used for α0.

Finally, we find x2 using the same method as that used to find x1.

The result, x2, is a "better" approximation to the system's solution than x1 and x0. If exact arithmetic were to be used in this example instead of limited-precision, then the exact solution would theoretically have been reached after n = 2 iterations (n being the order of the system).

Finite Termination Property

[edit]

Under exact arithmetic, the number of iterations required is no more than the order of the matrix. This behavior is known as the finite termination property of the conjugate gradient method. It refers to the method's ability to reach the exact solution of a linear system in a finite number of steps—at most equal to the dimension of the system—when exact arithmetic is used. This property arises from the fact that, at each iteration, the method generates a residual vector that is orthogonal to all previous residuals. These residuals form a mutually orthogonal set.

In an n-dimensional space, it is impossible to construct more than n linearly independent and mutually orthogonal vectors unless one of them is the zero vector. Therefore, once a zero residual appears, the method has reached the solution and must terminate. This ensures that the conjugate gradient method converges in at most n steps.

To demonstrate this, consider the system:

We start from an initial guess . Since is symmetric positive-definite and the system is 2-dimensional, the conjugate gradient method should find the exact solution in no more than 2 steps. The following MATLAB code demonstrates this behavior:

A = [3, -2; -2, 4];
x_true = [1; 1];
b = A * x_true;

x = [1; 2];             % initial guess
r = b - A * x;
p = r;

for k = 1:2
    Ap = A * p;
    alpha = (r' * r) / (p' * Ap);
    x = x + alpha * p;
    r_new = r - alpha * Ap;
    beta = (r_new' * r_new) / (r' * r);
    p = r_new + beta * p;
    r = r_new;
end

disp('Exact solution:');
disp(x);

The output confirms that the method reaches after two iterations, consistent with the theoretical prediction. This example illustrates how the conjugate gradient method behaves as a direct method under idealized conditions.

Application to Sparse Systems

[edit]

The finite termination property also has practical implications in solving large sparse systems, which frequently arise in scientific and engineering applications. For instance, discretizing the two-dimensional Laplace equation using finite differences on a uniform grid leads to a sparse linear system , where is symmetric and positive definite.

Using a interior grid yields a system, and the coefficient matrix has a five-point stencil pattern. Each row of contains at most five nonzero entries corresponding to the central point and its immediate neighbors. For example, the matrix generated from such a grid may look like:

Although the system dimension is 25, the conjugate gradient method is theoretically guaranteed to terminate in at most 25 iterations under exact arithmetic. In practice, convergence often occurs in far fewer steps due to the matrix's spectral properties. This efficiency makes CGM particularly attractive for solving large-scale systems arising from partial differential equations, such as those found in heat conduction, fluid dynamics, and electrostatics.

Convergence properties

[edit]

The conjugate gradient method can theoretically be viewed as a direct method, as in the absence of round-off error it produces the exact solution after a finite number of iterations, which is not larger than the size of the matrix. In practice, the exact solution is never obtained since the conjugate gradient method is unstable with respect to even small perturbations, e.g., most directions are not in practice conjugate, due to a degenerative nature of generating the Krylov subspaces.

As an iterative method, the conjugate gradient method monotonically (in the energy norm) improves approximations to the exact solution and may reach the required tolerance after a relatively small (compared to the problem size) number of iterations. The improvement is typically linear and its speed is determined by the condition number of the system matrix : the larger is, the slower the improvement.[8]

However, an interesting case appears when the eigenvalues are spaced logarithmically for a large symmetric matrix. For example, let where is a random orthogonal matrix and is a diagonal matrix with eigenvalues ranging from to , spaced logarithmically. Despite the finite termination property of CGM, where the exact solution should theoretically be reached in at most steps, the method may exhibit stagnation in convergence. In such a scenario, even after many more iterations—e.g., ten times the matrix size—the error may only decrease modestly (e.g., to ). Moreover, the iterative error may oscillate significantly, making it unreliable as a stopping condition. This poor convergence is not explained by the condition number alone (e.g., ), but rather by the eigenvalue distribution itself. When the eigenvalues are more evenly spaced or randomly distributed, such convergence issues are typically absent, highlighting that CGM performance depends not only on but also on how the eigenvalues are distributed.[9]

If is large, preconditioning is commonly used to replace the original system with such that is smaller than , see below.

Convergence theorem

[edit]

Define a subset of polynomials as

where is the set of polynomials of maximal degree .

Let be the iterative approximations of the exact solution , and define the errors as . Now, the rate of convergence can be approximated as [4][10]

where denotes the spectrum, and denotes the condition number.

This shows iterations suffices to reduce the error to for any .

Note, the important limit when tends to

This limit shows a faster convergence rate compared to the iterative methods of Jacobi or Gauss–Seidel which scale as .

No round-off error is assumed in the convergence theorem, but the convergence bound is commonly valid in practice as theoretically explained[5] by Anne Greenbaum.

Practical convergence

[edit]

If initialized randomly, the first stage of iterations is often the fastest, as the error is eliminated within the Krylov subspace that initially reflects a smaller effective condition number. The second stage of convergence is typically well defined by the theoretical convergence bound with , but may be super-linear, depending on a distribution of the spectrum of the matrix and the spectral distribution of the error.[5] In the last stage, the smallest attainable accuracy is reached and the convergence stalls or the method may even start diverging. In typical scientific computing applications in double-precision floating-point format for matrices of large sizes, the conjugate gradient method uses a stopping criterion with a tolerance that terminates the iterations during the first or second stage.

The preconditioned conjugate gradient method

[edit]

In most cases, preconditioning is necessary to ensure fast convergence of the conjugate gradient method. If is symmetric positive-definite and has a better condition number than a preconditioned conjugate gradient method can be used. It takes the following form:[11]

repeat
if rk+1 is sufficiently small then exit loop end if
end repeat
The result is xk+1

The above formulation is equivalent to applying the regular conjugate gradient method to the preconditioned system[12]

where

The Cholesky decomposition of the preconditioner must be used to keep the symmetry (and positive definiteness) of the system. However, this decomposition does not need to be computed, and it is sufficient to know . It can be shown that has the same spectrum as .

The preconditioner matrix has to be symmetric positive-definite and fixed, i.e., cannot change from iteration to iteration. If any of these assumptions on the preconditioner is violated, the behavior of the preconditioned conjugate gradient method may become unpredictable.

An example of a commonly used preconditioner is the incomplete Cholesky factorization.[13]

Using the preconditioner in practice

[edit]

It is important to keep in mind that we don't want to invert the matrix explicitly in order to get for use it in the process, since inverting would take more time/computational resources than solving the conjugate gradient algorithm itself. As an example, let's say that we are using a preconditioner coming from incomplete Cholesky factorization. The resulting matrix is the lower triangular matrix , and the preconditioner matrix is:

Then we have to solve:

But:

Then:

Let's take an intermediary vector :

Since and and known, and is lower triangular, solving for is easy and computationally cheap by using forward substitution. Then, we substitute in the original equation:

Since and are known, and is upper triangular, solving for is easy and computationally cheap by using backward substitution.

Using this method, there is no need to invert or explicitly at all, and we still obtain .

The flexible preconditioned conjugate gradient method

[edit]

In numerically challenging applications, sophisticated preconditioners are used, which may lead to variable preconditioning, changing between iterations. Even if the preconditioner is symmetric positive-definite on every iteration, the fact that it may change makes the arguments above invalid, and in practical tests leads to a significant slow down of the convergence of the algorithm presented above. Using the Polak–Ribière formula

instead of the Fletcher–Reeves formula

may dramatically improve the convergence in this case.[14] This version of the preconditioned conjugate gradient method can be called[15] flexible, as it allows for variable preconditioning. The flexible version is also shown[16] to be robust even if the preconditioner is not symmetric positive definite (SPD).

The implementation of the flexible version requires storing an extra vector. For a fixed SPD preconditioner, so both formulas for βk are equivalent in exact arithmetic, i.e., without the round-off error.

The mathematical explanation of the better convergence behavior of the method with the Polak–Ribière formula is that the method is locally optimal in this case, in particular, it does not converge slower than the locally optimal steepest descent method.[17]

Vs. the locally optimal steepest descent method

[edit]

In both the original and the preconditioned conjugate gradient methods one only needs to set in order to make them locally optimal, using the line search, steepest descent methods. With this substitution, vectors p are always the same as vectors z, so there is no need to store vectors p. Thus, every iteration of these steepest descent methods is a bit cheaper compared to that for the conjugate gradient methods. However, the latter converge faster, unless a (highly) variable and/or non-SPD preconditioner is used, see above.

Conjugate gradient method as optimal feedback controller for double integrator

[edit]

The conjugate gradient method can also be derived using optimal control theory.[18] In this approach, the conjugate gradient method falls out as an optimal feedback controller, for the double integrator system, The quantities and are variable feedback gains.[18]

Conjugate gradient on the normal equations

[edit]

The conjugate gradient method can be applied to an arbitrary n-by-m matrix by applying it to normal equations ATA and right-hand side vector ATb, since ATA is a symmetric positive-semidefinite matrix for any A. The result is conjugate gradient on the normal equations (CGN or CGNR).

ATAx = ATb

As an iterative method, it is not necessary to form ATA explicitly in memory but only to perform the matrix–vector and transpose matrix–vector multiplications. Therefore, CGNR is particularly useful when A is a sparse matrix since these operations are usually extremely efficient. However the downside of forming the normal equations is that the condition number κ(ATA) is equal to κ2(A) and so the rate of convergence of CGNR may be slow and the quality of the approximate solution may be sensitive to roundoff errors. Finding a good preconditioner is often an important part of using the CGNR method.

Several algorithms have been proposed (e.g., CGLS, LSQR). The LSQR algorithm purportedly has the best numerical stability when A is ill-conditioned, i.e., A has a large condition number.

Conjugate gradient method for complex Hermitian matrices

[edit]

The conjugate gradient method with a trivial modification is extendable to solving, given complex-valued matrix A and vector b, the system of linear equations for the complex-valued vector x, where A is Hermitian (i.e., A' = A) and positive-definite matrix, and the symbol ' denotes the conjugate transpose. The trivial modification is simply substituting the conjugate transpose for the real transpose everywhere.

Advantages and disadvantages

[edit]

The advantages and disadvantages of the conjugate gradient methods are summarized in the lecture notes by Nemirovsky and BenTal.[19]: Sec.7.3 

A pathological example

[edit]

This example is from [20] Let , and defineSince is invertible, there exists a unique solution to . Solving it by conjugate gradient descent gives us rather bad convergence:In words, during the CG process, the error grows exponentially, until it suddenly becomes zero as the unique solution is found.

See also

[edit]

References

[edit]

Further reading

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
The conjugate gradient method is an iterative algorithm for numerically solving systems of linear equations Ax=bAx = b, where AA is an n×nn \times n symmetric positive-definite matrix. Developed by Magnus R. Hestenes and Eduard Stiefel in 1952, it constructs a sequence of AA-conjugate search directions—vectors pkp_k satisfying piTApj=0p_i^T A p_j = 0 for iji \neq j—to minimize the associated quadratic functional 12xTAxbTx\frac{1}{2} x^T A x - b^T x, whose is the residual r=bAxr = b - Ax. In exact arithmetic, the method converges to the unique solution in at most nn iterations, as the residuals become AA-orthogonal, spanning the until the error is eliminated. This approach excels in handling large, sparse systems arising in scientific computing, requiring only storage for a few vectors and matrix-vector products per , making it more memory-efficient than direct methods like for high-dimensional problems. Key advantages include its robustness to ill-conditioning when preconditioned—using a symmetric positive-definite matrix MM to approximate A1A^{-1} and accelerate convergence—and its theoretical error bound, which decreases by a factor related to the κ(A)\kappa(A) per step. Extensions, such as nonlinear conjugate gradient variants, apply it to unconstrained optimization by adapting the direction update for non-quadratic objectives. Notable applications span partial differential equations (PDEs) discretized via finite elements or finite differences, where sparse AA models physical phenomena like heat diffusion or ; optimization in for least-squares problems; and preconditioned solvers in . Despite finite-precision effects potentially slowing convergence beyond the theoretical nn steps, preconditioning techniques like enhance practical performance, establishing the method as a cornerstone of iterative linear algebra.

Mathematical Background

Quadratic Optimization Problem

The conjugate gradient method addresses the problem of minimizing a quadratic function of the form
f(x)=12xTAxbTx+c,f(\mathbf{x}) = \frac{1}{2} \mathbf{x}^T A \mathbf{x} - \mathbf{b}^T \mathbf{x} + c,
where AA is an n×nn \times n symmetric positive definite matrix, bRn\mathbf{b} \in \mathbb{R}^n, cRc \in \mathbb{R}, and xRn\mathbf{x} \in \mathbb{R}^n. This formulation assumes AA is symmetric, ensuring the quadratic form is well-defined, and positive definite, guaranteeing a unique global minimum.
The minimizer x\mathbf{x}^* of f(x)f(\mathbf{x}) satisfies the equivalent
Ax=b.A \mathbf{x}^* = \mathbf{b}.
This equivalence follows from setting the f(x)=Axb=0\nabla f(\mathbf{x}) = A \mathbf{x} - \mathbf{b} = \mathbf{0}, which yields the normal equations for the system. The method operates in the Rn\mathbb{R}^n equipped with the standard inner product p,q=pTq\langle \mathbf{p}, \mathbf{q} \rangle = \mathbf{p}^T \mathbf{q}. Additionally, an A-inner product is defined as p,qA=pTAq\langle \mathbf{p}, \mathbf{q} \rangle_A = \mathbf{p}^T A \mathbf{q}, which induces a geometry aligned with the and plays a key role in the method's convergence properties.
The analysis of the conjugate gradient method initially assumes exact arithmetic, with no rounding errors, under which the algorithm terminates in at most nn iterations. This idealization establishes the theoretical foundation, though practical implementations account for finite-precision effects.

Conjugate Directions and Vectors

In the conjugate gradient method, the core idea revolves around directions that are conjugate with respect to a symmetric positive AA. Two nonzero vectors pp and qq are defined as AA-conjugate if pTAq=0p^T A q = 0. For a set of vectors {pi}i=0n1\{p_i\}_{i=0}^{n-1}, they are mutually AA-conjugate if piTApj=0p_i^T A p_j = 0 for all iji \neq j. This conjugacy condition generalizes from the standard Euclidean inner product to the AA-weighted inner product u,vA=uTAv\langle u, v \rangle_A = u^T A v, providing a framework for efficient exploration of the quadratic optimization landscape. A fundamental property of mutually AA-conjugate directions is that any nn linearly independent such directions form a basis for Rn\mathbb{R}^n. In the context of minimizing the f(x)=12xTAxbTxf(x) = \frac{1}{2} x^T A x - b^T x, starting from an initial point, exact minimization can be achieved in at most nn line searches along these directions. Each step minimizes ff over the affine subspace spanned by the initial point and the conjugate directions up to that iteration, ensuring no redundant effort in the search. This spanning property exploits the of the ellipsoid level sets defined by AA, allowing the method to converge to the global minimum without revisiting previously optimized subspaces. During the conjugate gradient iterations, the residual vectors rk=bAxkr_k = b - A x_k are orthogonal, satisfying riTrj=0r_i^T r_j = 0 for iji \neq j. The error vectors ek=xxke_k = x^* - x_k exhibit A-orthogonality, satisfying eiTAej=0e_i^T A e_j = 0 for iji \neq j. These properties, alongside the conjugacy of the search directions, ensure efficient subspace minimization and rapid error reduction. The term "conjugate gradient" originates from this interplay between conjugate directions and the gradients (residuals) in the optimization process, as coined by Hestenes and Stiefel in their seminal 1952 paper.

Derivation of the Method

Direct Method Perspective

The conjugate gradient method can be viewed as a direct solver for systems of linear equations Ax=bAx = b, where AA is an n×nn \times n symmetric positive definite (SPD) matrix, guaranteeing an exact solution in at most nn steps under exact arithmetic. This perspective treats the method as a means to expand the solution in a basis of AA-conjugate directions, which form an orthogonal set with respect to the inner product u,vA=uTAv\langle \mathbf{u}, \mathbf{v} \rangle_A = \mathbf{u}^T A \mathbf{v}. Starting from an initial guess x0\mathbf{x}_0, the residual is r0=bAx0\mathbf{r}_0 = b - A \mathbf{x}_0, and the search directions pk\mathbf{p}_k are generated iteratively such that piTApj=0\mathbf{p}_i^T A \mathbf{p}_j = 0 for iji \neq j. The exact solution is then expressed as x=x0+k=1nαkpk,\mathbf{x}^* = \mathbf{x}_0 + \sum_{k=1}^n \alpha_k \mathbf{p}_k, where the coefficients αk\alpha_k are chosen to minimize the quadratic functional f(x)=12xTAxbTxf(\mathbf{x}) = \frac{1}{2} \mathbf{x}^T A \mathbf{x} - \mathbf{b}^T \mathbf{x} along each direction, yielding αk=rkTrkpkTApk.\alpha_k = \frac{\mathbf{r}_k^T \mathbf{r}_k}{\mathbf{p}_k^T A \mathbf{p}_k}. This step-wise minimization ensures that each update xk+1=xk+αkpk\mathbf{x}_{k+1} = \mathbf{x}_k + \alpha_k \mathbf{p}_k reduces the residual rk+1=rkαkApk\mathbf{r}_{k+1} = \mathbf{r}_k - \alpha_k A \mathbf{p}_k, with residuals remaining orthogonal: riTrj=0\mathbf{r}_i^T \mathbf{r}_j = 0 for iji \neq j. The finite termination in at most nn steps follows from the dimensionality of the . Since AA is SPD, the conjugate directions {p1,,pn}\{\mathbf{p}_1, \dots, \mathbf{p}_n\} form a basis for Rn\mathbb{R}^n, spanning the entire error e0=xx0\mathbf{e}_0 = \mathbf{x}^* - \mathbf{x}_0. After nn iterations, the residual rn=0\mathbf{r}_n = 0, as the orthogonal residuals {r0,,rn1}\{\mathbf{r}_0, \dots, \mathbf{r}_{n-1}\} span Rn\mathbb{R}^n, and the method exactly solves the system. This property holds because the AA-inner product induces a valid Euclidean structure, allowing the conjugate basis to complete without linear dependence before nn steps. In practice, for ill-conditioned AA, termination may occur effectively earlier if the initial residual lies in a lower-dimensional , but the worst-case bound is nn. This direct solver interpretation relates closely to the Gram-Schmidt orthogonalization process applied to the Kk(r0,A)=\span{r0,Ar0,,Ak1r0}\mathcal{K}_k(\mathbf{r}_0, A) = \span\{\mathbf{r}_0, A\mathbf{r}_0, \dots, A^{k-1}\mathbf{r}_0\}. The residuals rk\mathbf{r}_k are AA-orthogonalized versions of the Krylov basis vectors, and the search directions pk\mathbf{p}_k are obtained by AA-orthogonalizing the successive residuals against previous directions, mirroring the Gram-Schmidt procedure in the AA-inner product. Specifically, the conjugacy condition ensures that each new direction is orthogonal to the span of prior ApjA \mathbf{p}_j, which aligns with the growing Krylov subspace of dimension kk at step kk. This connection underscores why the method terminates in nn steps: the full Krylov subspace Kn(r0,A)\mathcal{K}_n(\mathbf{r}_0, A) equals Rn\mathbb{R}^n for SPD AA with distinct eigenvalues or generic r0\mathbf{r}_0. To maintain conjugacy without explicit orthogonalization, the update for the next direction is pk+1=rk+1+βkpk\mathbf{p}_{k+1} = \mathbf{r}_{k+1} + \beta_k \mathbf{p}_k, where βk\beta_k is derived to ensure pk+1TApj=0\mathbf{p}_{k+1}^T A \mathbf{p}_j = 0 for all jkj \leq k. Imposing this on j=kj = k gives rk+1TApk+βkpkTApk=0\mathbf{r}_{k+1}^T A \mathbf{p}_k + \beta_k \mathbf{p}_k^T A \mathbf{p}_k = 0. Since rk+1=rkαkApk\mathbf{r}_{k+1} = \mathbf{r}_k - \alpha_k A \mathbf{p}_k and residuals are orthogonal to prior residuals (with pk\mathbf{p}_k in the span of previous rj\mathbf{r}_j), the cross term simplifies using rkTApk=rkTrk/αk\mathbf{r}_k^T A \mathbf{p}_k = \mathbf{r}_k^T \mathbf{r}_k / \alpha_k, leading to βk=rk+1Trk+1rkTrk.\beta_k = \frac{\mathbf{r}_{k+1}^T \mathbf{r}_{k+1}}{\mathbf{r}_k^T \mathbf{r}_k}. This formula preserves the three-term recurrence, avoiding the need to store the full basis and enabling the direct expansion in finite steps.

Iterative Method Perspective

The conjugate gradient method serves as an iterative approximation scheme for solving the symmetric positive definite linear system Ax=bAx = b, where the goal is to minimize the associated quadratic functional f(x)=12xTAxbTxf(x) = \frac{1}{2} x^T A x - b^T x. At step kk, the iterate xkx_k is selected to minimize the quadratic functional f(xk)f(x_k) over the kk-th Krylov subspace Kk=\SPAN{r0,Ar0,,Ak1r0}\mathcal{K}_k = \SPAN\{r_0, A r_0, \dots, A^{k-1} r_0\}, where r0=bAx0r_0 = b - A x_0 (equivalently, minimizing the A-norm of the error xkxA\|x_k - x^*\|_A over the affine space x0+Kkx_0 + \mathcal{K}_k). This subspace minimization ensures that xkx_k provides the best approximation in the A-norm to the exact solution within the affine space x0+Kkx_0 + \mathcal{K}_k. The iteration proceeds by advancing along a conjugate search direction pkp_k, yielding the update xk+1=xk+αkpkx_{k+1} = x_k + \alpha_k p_k, where αk>0\alpha_k > 0 is a step length chosen to minimize f(xk+1)f(x_{k+1}) along the line xk+αpkx_k + \alpha p_k. This condition implies αk=rkTrkpkTApk\alpha_k = \frac{r_k^T r_k}{p_k^T A p_k}, which enforces the pkTrk+1=0p_k^T r_{k+1} = 0 upon updating the residual as rk+1=rkαkApkr_{k+1} = r_k - \alpha_k A p_k. The resulting residual rk+1r_{k+1} lies in Kk+1\mathcal{K}_{k+1} and is orthogonal to all previous residuals {r0,,rk}\{r_0, \dots, r_k\}, a property that maintains the minimization over expanding Krylov subspaces. To generate the next direction, pk+1=rk+1+βkpkp_{k+1} = r_{k+1} + \beta_k p_k, where βk=rk+1Trk+1rkTrk\beta_k = \frac{r_{k+1}^T r_{k+1}}{r_k^T r_k}, ensuring that the directions remain A-conjugate (piTApj=0p_i^T A p_j = 0 for iji \neq j) and that the residuals remain mutually orthogonal. This conjugacy property, combined with the three-term recurrence for the residuals and directions, enables a short-recurrence formulation that avoids explicit construction of the full Krylov basis, requiring only O(n)O(n) storage and work per iteration for an n×nn \times n system. The method thus efficiently approximates the exact minimizer of f(x)f(x) in finite steps for the quadratic case.

The Algorithm

Core Steps and Updates

The conjugate gradient method is implemented via an initialization phase followed by an iterative loop that computes step lengths, updates the approximate solution and residual, and maintains conjugate search directions. This , originally proposed by Hestenes and Stiefel, solves the Ax=bAx = b where AA is symmetric positive definite, typically in at most nn iterations for an n×nn \times n system in exact arithmetic. Initialization requires selecting an arbitrary initial x0x_0. The initial residual vector is then formed as r0=bAx0,r_0 = b - A x_0, and the initial search direction is set to p0=r0.p_0 = r_0. These choices ensure the method begins with a direction aligned with the of the associated quadratic objective. The core iteration, for k=0,1,2,k = 0, 1, 2, \dots, proceeds as follows. First, compute the step size αk=rkTrkpkTApk.\alpha_k = \frac{r_k^T r_k}{p_k^T A p_k}. Update the solution and residual recursively: xk+1=xk+αkpk,rk+1=rkαkApk.x_{k+1} = x_k + \alpha_k p_k, \quad r_{k+1} = r_k - \alpha_k A p_k. Next, compute the conjugacy parameter βk=rk+1Trk+1rkTrk,\beta_k = \frac{r_{k+1}^T r_{k+1}}{r_k^T r_k}, and update the search direction: pk+1=rk+1+βkpk.p_{k+1} = r_{k+1} + \beta_k p_k. The formulas for αk\alpha_k and βk\beta_k arise from conditions in the residual and conjugacy in the directions, ensuring short-recurrence . Due to , the recursive residual update can accumulate roundoff errors, leading to loss of conjugacy. To mitigate this, the residual should be recomputed explicitly at intervals as rk+1=bAxk+1r_{k+1} = b - A x_{k+1}, particularly after a fixed number of steps or when rk+1Trk\| r_{k+1}^T r_k \| becomes unreliable. Stopping criteria include a tolerance on the residual norm, such as rk2<ϵb2\| r_k \|_2 < \epsilon \| b \|_2 for a relative tolerance ϵ\epsilon, or a maximum iteration count exceeding the problem dimension to handle ill-conditioning. The full algorithm in pseudocode form is:

Input: A (symmetric positive definite), b, x_0 (initial guess), ε (tolerance), max_iter Output: x (approximate solution) r ← b - A x_0 p ← r rsold ← r^T r for k = 0 to max_iter - 1 do if √rsold < ε then break end if Ap ← A p α ← rsold / (p^T Ap) x ← x + α p r ← r - α Ap rsnew ← r^T r if √rsnew < ε then break end if β ← rsnew / rsold p ← r + β p rsold ← rsnew end for // Optional: Recompute r = b - A x for accuracy

Input: A (symmetric positive definite), b, x_0 (initial guess), ε (tolerance), max_iter Output: x (approximate solution) r ← b - A x_0 p ← r rsold ← r^T r for k = 0 to max_iter - 1 do if √rsold < ε then break end if Ap ← A p α ← rsold / (p^T Ap) x ← x + α p r ← r - α Ap rsnew ← r^T r if √rsnew < ε then break end if β ← rsnew / rsold p ← r + β p rsold ← rsnew end for // Optional: Recompute r = b - A x for accuracy

This implementation uses dot products for efficiency and monitors the squared residual norm to avoid square roots until checking the criterion.

Practical Considerations and Restarting

In practice, rounding errors in finite-precision arithmetic can accumulate during the iterations of the conjugate gradient method, leading to a gradual loss of orthogonality among the residual vectors and potentially causing the algorithm to stall or converge more slowly than expected. To counteract this, a widely adopted implementation strategy involves periodic restarting, where the algorithm is reset every m iterations—typically with m around 20 to 30 for problems of moderate size—by setting the search direction equal to the current residual, pkm=rkmp_{km} = r_{km}. This simple reset reinitiates the generation of conjugate directions from the updated residual, thereby restoring approximate orthogonality and enhancing overall numerical stability, though it may introduce a minor overhead in convergence speed for ill-conditioned systems. Another key consideration for numerical robustness is the computation of the parameter βk\beta_k, which updates the search direction. Theoretically, rk+1Trk=0r_{k+1}^T r_k = 0 due to orthogonality, but in floating-point arithmetic, this dot product is nonzero and small, leading to potential cancellation errors if used in the formula βk=rk+1TrkrkTrk\beta_k = \frac{r_{k+1}^T r_k}{r_k^T r_k}. Instead, practitioners avoid this by employing the equivalent but more stable expression βk=rk+12rk2\beta_k = \frac{\| r_{k+1} \|^2}{\| r_k \|^2}, which relies solely on positive quantities (squared residual norms) and better preserves the method's properties under rounding perturbations. Regarding efficiency, the conjugate gradient method excels in scenarios with large sparse matrices, as it requires only O(n) storage space for a handful of n-dimensional vectors (such as the iterate, residual, search direction, and auxiliary products like ApAp), without needing to store the full matrix A. Operations are performed via on-the-fly matrix-vector multiplications ApAp, which are computationally inexpensive for sparse representations, making the method scalable to systems with millions of unknowns. The core iterative loop, incorporating stable βk\beta_k computation and restarting, can be implemented succinctly in languages like MATLAB or Julia. Below is example pseudocode in MATLAB syntax, assuming A is a function handle for sparse matrix-vector multiplication and restart_interval is set to 30:

function [x, k] = cg_restart(A, b, x0, tol, maxit, restart_interval) x = x0; r = b - A(x); rsold = dot(r, r); p = r; k = 0; if sqrt(rsold) < tol, return; end while k < maxit k = k + 1; if mod(k, restart_interval) == 0 p = r; rsold = dot(r, r); end Ap = A(p); alpha = rsold / dot(p, Ap); x = x + alpha * p; r = r - alpha * Ap; rsnew = dot(r, r); if sqrt(rsnew) < tol, break; end beta = rsnew / rsold; p = r + beta * p; rsold = rsnew; end end

function [x, k] = cg_restart(A, b, x0, tol, maxit, restart_interval) x = x0; r = b - A(x); rsold = dot(r, r); p = r; k = 0; if sqrt(rsold) < tol, return; end while k < maxit k = k + 1; if mod(k, restart_interval) == 0 p = r; rsold = dot(r, r); end Ap = A(p); alpha = rsold / dot(p, Ap); x = x + alpha * p; r = r - alpha * Ap; rsnew = dot(r, r); if sqrt(rsnew) < tol, break; end beta = rsnew / rsold; p = r + beta * p; rsold = rsnew; end end

This formulation ensures efficient execution while mitigating common numerical pitfalls through the norm-based βk\beta_k and explicit restarts.

Numerical Example

To illustrate the conjugate gradient method, consider solving the linear system Ax=bAx = b, where AA is the symmetric positive definite 3×3 matrix A=(321262127),A = \begin{pmatrix} 3 & 2 & 1 \\ 2 & 6 & 2 \\ 1 & 2 & 7 \end{pmatrix},
Add your contribution
Related Hubs
User Avatar
No comments yet.