Skip to main content
`Ctrl`+`K`
scipy.sparse.linalg.

# cg

scipy.sparse.linalg.cg(A, b, x0=None, *, rtol=1e-05, atol=0.0, maxiter=None, M=None, callback=None)

  Solve `Ax = b` with the Conjugate Gradient method, for a symmetric, positive-definite A.

  Parameters:
    A{sparse array, ndarray, LinearOperator}

      The real or complex N-by-N matrix of the linear system. A must represent a hermitian, positive definite matrix. Alternatively, A can be a linear operator which can produce `Ax` using, e.g., `scipy.sparse.linalg.LinearOperator`.

    bndarray

      Right hand side of the linear system. Has shape (N,) or (N,1).

    x0ndarray

      Starting guess for the solution.

    rtol, atolfloat, optional

      Parameters for the convergence test. For convergence, `norm(b - A @ x) <= max(rtol*norm(b), atol)` should be satisfied. The default is `atol=0.` and `rtol=1e-5`.

    maxiterinteger

      Maximum number of iterations. Iteration will stop after maxiter steps even if the specified tolerance has not been achieved.

    M{sparse array, ndarray, LinearOperator}

      Preconditioner for A. M must represent a hermitian, positive definite matrix. It should approximate the inverse of A (see Notes). Effective preconditioning dramatically improves the rate of convergence, which implies that fewer iterations are needed to reach a given error tolerance.

    callbackfunction

      User-supplied function to call after each iteration. It is called as `callback(xk)`, where `xk` is the current solution vector.

  Returns:
    xndarray

      The converged solution.

    infointeger
      Provides convergence information:

        0 : successful exit >0 : convergence to tolerance not achieved, number of iterations

  Notes

  The preconditioner M should be a matrix such that `M @ A` has a smaller condition number than A, see [2].

  References

  [1]

  “Conjugate Gradient Method, Wikipedia, https://en.wikipedia.org/wiki/Conjugate_gradient_method

  [2]

  “Preconditioner”, Wikipedia, https://en.wikipedia.org/wiki/Preconditioner

  Examples

      >>> import numpy as np
      >>> from scipy.sparse import csc_array
      >>> from scipy.sparse.linalg import cg
      >>> P = np.array([[4, 0, 1, 0],
      ...               [0, 5, 0, 0],
      ...               [1, 0, 3, 2],
      ...               [0, 0, 2, 4]])
      >>> A = csc_array(P)
      >>> b = np.array([-1, -0.5, -1, 2])
      >>> x, exit_code = cg(A, b, atol=1e-5)
      >>> print(exit_code)    # 0 indicates successful convergence
      0
      >>> np.allclose(A.dot(x), b)
      True