stepik: https://stepik.org/a/260000
π Professional implementation and mathematical explanation of Conjugate Gradient (CG) and Sparse Conjugate Gradient methods for large-scale linear systems.
This repository provides a complete course-style implementation of:
- Conjugate Gradient (CG) algorithm
- Preconditioned Conjugate Gradient
- Sparse Conjugate Gradient
- Large-scale linear system solving
- Numerical stability analysis
- Optimization perspective of CG
conjugate gradient
conjugate gradient method
sparse conjugate gradient
pcg solver
cg solver python
large scale linear systems
numerical linear algebra
iterative solver
preconditioned conjugate gradient
optimization solver
python cg implementation
We solve:
Where:
-
$$A$$ β symmetric positive definite matrix -
$$x$$ β unknown vector -
$$b$$ β right-hand side
CG minimizes quadratic function:
Update rule:
Where:
-
$$p_k$$ β conjugate direction -
$$\alpha_k$$ β optimal step size
Step size:
Direction update:
Where:
For sparse matrices:
- Store matrix in CSR/CSC format
- Avoid dense multiplication
- Reduce memory complexity
Advantages:
β
Memory efficient
β
Faster computation
β
Scalable to large systems
CG is used in:
- Finite element methods
- Physics simulations
- Machine learning
- PDE solvers
- Large sparse systems
- Scientific computing
It is one of the most important iterative solvers.
conjugate-gradient-sparse-cg-solver-course/
β
βββ README.md
βββ LICENSE
βββ CITATION.cff
βββ requirements.txt
β
βββ src/
β βββ cg_solver.py
β βββ sparse_cg.py
β βββ preconditioner.py
β
βββ examples/
β βββ demo.py
β
βββ docs/
β βββ theory.md
β βββ convergence.md
β
βββ images/
β βββ convergence_plot.png
β
βββ index.html
Clean structure improves:
β Search ranking
β Professional appearance
β Research credibility
import numpy as np
def conjugate_gradient(A, b, x0=None, tol=1e-8, max_iter=1000):
n = len(b)
x = np.zeros(n) if x0 is None else x0
r = b - A @ x
p = r.copy()
for _ in range(max_iter):
Ap = A @ p
alpha = (r @ r) / (p @ Ap)
x = x + alpha * p
r_new = r - alpha * Ap
if np.linalg.norm(r_new) < tol:
break
beta = (r_new @ r_new) / (r @ r)
p = r_new + beta * p
r = r_new
return xpip install -r requirements.txtRun example:
python examples/demo.pyAdd:
- Residual norm vs iteration
- Convergence curve
- Sparse matrix structure plot
Example:
import matplotlib.pyplot as plt
plt.plot(residual_history)
plt.xlabel("Iteration")
plt.ylabel("Residual Norm")
plt.title("CG Convergence")
plt.show()