-
-
Save danielsuo/714fbc857c1bb716458f89d45081da86 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cg(A, b, x0=None, maxiter=None, tol=1e-5): | |
x = x0 or np.zeros_like(b) | |
k = 0 | |
kmax = maxiter or len(b) | |
r = b - A @ x | |
p = r | |
d_o = np.dot(r, r) | |
d_n = d_o | |
while k < kmax and d_n > tol ** 2 * d_o: | |
a = float(d_n / (p.T @ (A @ p))) | |
x += a * p | |
r -= a * (A @ p) | |
d_o = d_n | |
d_n = np.dot(r, r) | |
beta = float(d_n / d_o) | |
p = r + beta * p | |
k += 1 | |
return x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment