Sparse iterative solvers help solve big systems of equations quickly when most values are zero. They save time and memory.
Sparse iterative solvers (gmres, cg) in SciPy
Start learning this pattern below
Jump into concepts and practice - no test required
from scipy.sparse.linalg import gmres, cg # gmres(A, b, tol=1e-5, maxiter=None) # cg(A, b, tol=1e-5, maxiter=None) # A: sparse matrix or linear operator # b: right-hand side vector # tol: tolerance for convergence # maxiter: maximum iterations allowed
gmres works well for general matrices.
cg is faster but only works if the matrix is symmetric and positive definite.
gmres to solve Ax = b for a sparse matrix A.from scipy.sparse.linalg import gmres import numpy as np from scipy.sparse import diags A = diags([2, 1, 3], [0, -1, 1], shape=(3,3)) b = np.array([1, 2, 3]) x, info = gmres(A, b) print(x)
cg for symmetric positive definite sparse matrix A.from scipy.sparse.linalg import cg import numpy as np from scipy.sparse import diags A = diags([4, 1, 1], [0, -1, 1], shape=(3,3)) b = np.array([1, 2, 3]) x, info = cg(A, b) print(x)
This program creates a small sparse matrix and solves the system Ax = b using both gmres and cg solvers. It prints the solutions and info codes where 0 means the solver succeeded.
from scipy.sparse.linalg import gmres, cg import numpy as np from scipy.sparse import diags # Create a sparse matrix A # Diagonal values: main diagonal 4, sub diagonal 1, super diagonal 1 A = diags([4, 1, 1], [0, -1, 1], shape=(3,3)) # Right-hand side vector b b = np.array([1, 2, 3]) # Solve using gmres x_gmres, info_gmres = gmres(A, b, tol=1e-8) # Solve using cg x_cg, info_cg = cg(A, b, tol=1e-8) print("Solution with gmres:", x_gmres) print("Info gmres (0 means success):", info_gmres) print("Solution with cg:", x_cg) print("Info cg (0 means success):", info_cg)
Check the info output: 0 means the solver found a solution successfully.
Set tol smaller for more accurate results but slower computation.
cg requires the matrix to be symmetric and positive definite; otherwise, it may fail.
Sparse iterative solvers like gmres and cg solve large sparse linear systems efficiently.
gmres works for general matrices; cg is faster but needs symmetric positive definite matrices.
They save memory and time by using the sparse structure instead of dense matrix methods.
Practice
scipy.sparse.linalg.cg is true?Solution
Step 1: Understand the requirements of
The conjugate gradient method (cgcg) is designed for symmetric positive definite matrices only.Step 2: Compare with other options
cgcannot solve any matrix (B is wrong), it is often faster thangmresfor suitable matrices (A is wrong), and it uses sparse methods, not dense (D is wrong).Final Answer:
cgrequires the matrix to be symmetric and positive definite. -> Option DQuick Check:
cgneeds symmetric positive definite matrix [OK]
- Thinking CG works for any matrix
- Confusing CG with GMRES
- Assuming CG uses dense matrix methods
Solution
Step 1: Recall the module location of GMRES
The GMRES solver is inscipy.sparse.linalg, so it must be imported from there.Step 2: Check the import syntax
Correct Python import syntax for a function isfrom module import function. from scipy.sparse.linalg import gmres matches this and the correct module.Final Answer:
from scipy.sparse.linalg import gmres -> Option BQuick Check:
Correct import syntax and module [OK]
- Importing from scipy.linalg instead of sparse.linalg
- Using incorrect import syntax
- Trying to import gmres directly from scipy.sparse
import numpy as np from scipy.sparse.linalg import cg from scipy.sparse import diags A = diags([1, 2, 1], [-1, 0, 1]).toarray() b = np.array([4, 6, 4]) x, info = cg(A, b) print(np.round(x, 2))
Solution
Step 1: Analyze the matrix and vector
The matrix A is tridiagonal with diagonals [1,2,1], which is symmetric positive definite. Vector b is [4,6,4].Step 2: Solve using conjugate gradient
Usingcg, the solution x satisfies Ax = b. The solution is approximately [1, 2, 1].Final Answer:
[1. 2. 1.] -> Option AQuick Check:
cg solves Ax=b with symmetric positive definite A [OK]
- Assuming cg fails on this matrix
- Confusing the solution vector with b
- Not rounding output before comparing
cg solver:import numpy as np from scipy.sparse.linalg import cg A = np.array([[0, 1], [1, 0]]) b = np.array([1, 2]) x, info = cg(A, b) print(x)
Solution
Step 1: Check matrix properties
Matrix A = [[0,1],[1,0]] is symmetric but not positive definite (its eigenvalues are 1 and -1).Step 2: Understand cg requirements
The conjugate gradient method requires A to be symmetric positive definite. Since A is not, cg will fail or not converge properly.Final Answer:
Matrix A is not symmetric positive definite, so cg will fail. -> Option AQuick Check:
cg needs symmetric positive definite matrix [OK]
- Ignoring matrix definiteness
- Assuming cg works for any symmetric matrix
- Thinking vector shape causes error
Ax = b efficiently?Solution
Step 1: Identify matrix properties
The matrix is large, sparse, and not symmetric positive definite, socgis not suitable.Step 2: Choose appropriate solver
gmrescan handle general matrices efficiently without requiring symmetry or positive definiteness.Step 3: Avoid dense conversion
Converting to dense wastes memory and time, so it is not efficient.Final Answer:
Usegmresbecause it works for general matrices. -> Option CQuick Check:
gmres handles general sparse matrices [OK]
- Trying to use cg on non-symmetric matrices
- Converting sparse to dense unnecessarily
- Thinking transposing fixes definiteness
