Skip to content

num::cg

Defined in header <linear/solvers/cg.hpp>

template <std::floating_point T, class MatVec>
krylov_result<T> cg(MatVec &&A, T *x, const T *b, idx n, T *work, T tol = T(1e-10),
                    idx max_iter = 1000);  // (1)

template <class Op, class V>
requires math::inner_product_space<V> && math::spd_operator<Op, V> &&
         std::floating_point<math::scalar_t<V>>
solver_result cg(const Op &A, const V &b, V &x, cg_options options = {});  // (2)

(1) Conjugate gradients for symmetric positive definite \(A\). Stops if some \(p^T A p \leq 0\).

(2) Solve \(A x = b\) by conjugate gradients for an operator claiming law::spd.

Parameters

  • A: Callable A(const T *x, T *y) writing \(y = Ax\).
  • x: Solution, used as the initial guess on entry.
  • b: Right-hand side, length n.
  • n: System dimension.
  • work: Caller-supplied scratch of length 3n.
  • tol: Absolute tolerance on \(\|r\|_2\).
  • max_iter: Iteration cap.
  • options: Tolerance on \(\|b - A x\|_2\) and iteration limit.

Return value

krylov_result: .iterations, .residual (final residual norm), .converged.

solver_result containing iteration count, final residual norm, and convergence boolean.

Exceptions

  • std::invalid_argument: If dimensions of A, b, and x do not match.

See also

assume_spd, pcg, minres, gmres