Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def cg(matvec, b, x0, disp=False, tol=1e-5, maxiter=None):
- hist = {'norm_r': []}
- if disp:
- print('%9s' % 'norm_r')
- def write_hist(hist, norm_r):
- hist['norm_r'].append(norm_r)
- def callback(x):
- r = matvec(x) - b
- norm_r = norm(r, np.inf)
- write_hist(hist, norm_r)
- if disp:
- print('%9.8f' % norm_r)
- callback(x0)
- xk = x0
- rk = matvec(xk) - b
- dk = -rk
- cnt_iter = 0
- while norm(rk, np.inf) > tol:
- alpha_k = rk.dot(rk) / dk.dot(matvec(dk))
- xk = xk + alpha_k * dk
- rk_new = rk + alpha_k * matvec(dk)
- beta_k = rk_new.dot(rk_new) / rk.dot(rk)
- rk = rk_new
- dk = -rk + beta_k * dk
- cnt_iter += 1
- callback(xk)
- if maxiter is not None and cnt_iter > maxiter:
- break
- return xk, hist
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement