Sparse iterative solvers (gmres, cg) in SciPy - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When solving large sparse systems, it is important to know how the time to find a solution grows as the system size increases.
We want to understand how the solver's work changes when the matrix and vector get bigger.
Analyze the time complexity of this sparse solver code using scipy.
import numpy as np
from scipy.sparse import diags
from scipy.sparse.linalg import cg
n = 1000
A = diags([1, 2, 1], [-1, 0, 1], shape=(n, n))
b = np.ones(n)
x, info = cg(A, b, tol=1e-5)
This code solves a system with a sparse tridiagonal matrix using the conjugate gradient method.
Look at what repeats inside the solver:
- Primary operation: Multiplying the sparse matrix by a vector repeatedly.
- How many times: The solver repeats this multiplication many times until it converges.
As the matrix size grows, each multiplication takes more time, and more steps may be needed.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | ~100 multiplications |
| 100 | ~1,000 multiplications |
| 1000 | ~10,000 multiplications |
Pattern observation: The total work grows roughly linearly with the size of the matrix times the number of iterations.
Time Complexity: O(k \times n)
This means the time grows with the number of iterations k times the size n of the matrix.
[X] Wrong: "The solver always takes the same number of steps regardless of matrix size."
[OK] Correct: Larger systems often need more iterations to reach a good solution, so time grows with both size and iteration count.
Understanding how iterative solvers scale helps you explain performance in real data science tasks involving large sparse data.
"What if the matrix was dense instead of sparse? How would the time complexity change?"
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
