The full experiment, SciPy's cg with and without a symmetric SOR preconditioner, against plain Jacobi, on four grid sizes:
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import cg, spsolve_triangular, LinearOperator
def poisson2d(N):
"""5-point Laplacian on an N x N grid: n = N**2 unknowns, 5 nonzeros per row."""
T = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(N, N))
I = sp.identity(N)
return (sp.kron(I, T) + sp.kron(T, I)).tocsr()
def jacobi(A, b, rtol, maxit=100000):
D = A.diagonal()
x = np.zeros_like(b)
for k in range(maxit):
r = b - A @ x
if np.linalg.norm(r) <= rtol * np.linalg.norm(b):
return k
x = x + r / D
return None
def ssor(A, w=1.5):
"""Symmetric SOR preconditioner: SPD whenever A is, so CG accepts it."""
D = sp.diags(A.diagonal())
lower = (D / w + sp.tril(A, -1)).tocsr()
upper = (D / w + sp.triu(A, 1)).tocsr()
d = A.diagonal() * (2 - w) / w
apply = lambda r: spsolve_triangular(upper, d * spsolve_triangular(lower, r), lower=False)
return LinearOperator(A.shape, apply)
def cg_iters(A, b, M=None):
count = [0]
x, info = cg(A, b, rtol=1e-8, M=M, callback=lambda xk: count.__setitem__(0, count[0] + 1))
assert info == 0, info
return count[0]
for N in (16, 32, 64, 128):
A = poisson2d(N)
b = np.ones(N * N)
kappa = 1 / np.tan(np.pi / (2 * (N + 1))) ** 2
print(f"N={N:3d} n={N*N:6d} cond={kappa:5.0f} jacobi={jacobi(A, b, 1e-8):5d} "
f"cg={cg_iters(A, b)} cg+ssor={cg_iters(A, b, ssor(A))}")
N= 16 n= 256 cond= 116 jacobi= 1064 cg=28 cg+ssor=15
N= 32 n= 1024 cond= 441 jacobi= 4020 cg=59 cg+ssor=23
N= 64 n= 4096 cond= 1712 jacobi=15599 cg=119 cg+ssor=39
N=128 n= 16384 cond= 6744 jacobi=61430 cg=239 cg+ssor=72
cond is computed from the closed form cot2(π/(2(N+1))), exact for this matrix. Reading down the columns: Jacobi multiplies by about 4 per row, CG by about 2, and preconditioned CG by less than 2. The SSOR preconditioner is chosen because it stays symmetric positive definite when A is, which CG requires; an incomplete LU factor is not symmetric and can make cg fail.