NUMCXX  0.13.20181108
Numerical library for small projects and teaching purposes
cg.hxx
Go to the documentation of this file.
1 namespace netlib
2 {
3 
25 
26  template < class Matrix, class Vector, class Preconditioner, class Real >
27  int
28  CG(const Matrix &A, Vector &x, const Vector &b,
29  const Preconditioner &M, int &max_iter, Real &tol)
30  {
31  Real resid;
32  Vector p, z, q;
33  Vector alpha(1), beta(1), rho(1), rho_1(1);
34 
35  Real normb = norm(b);
36  Vector r = b - A*x;
37 
38  if (normb == 0.0)
39  normb = 1;
40 
41  if ((resid = norm(r) / normb) <= tol) {
42  tol = resid;
43  max_iter = 0;
44  return 0;
45  }
46 
47  for (int i = 1; i <= max_iter; i++) {
48  // numcxx: was
49  // z=M.solve(r)
50  M.solve(z, r);
51  rho(0) = dot(r, z);
52 
53  if (i == 1)
54  p = z;
55  else {
56  beta(0) = rho(0) / rho_1(0);
57  p = z + beta(0) * p;
58  }
59 
60  q = A*p;
61  alpha(0) = rho(0) / dot(p, q);
62 
63  x += alpha(0) * p;
64  r -= alpha(0) * q;
65 
66  if ((resid = norm(r) / normb) <= tol) {
67  tol = resid;
68  max_iter = i;
69  return 0;
70  }
71 
72  rho_1(0) = rho(0);
73  }
74 
75  tol = resid;
76  return 1;
77  }
78 }
79 
int CG(const Matrix &A, Vector &x, const Vector &b, const Preconditioner &M, int &max_iter, Real &tol)
Iterative template routine – CG.
Definition: cg.hxx:28
Iterative template routines.
Definition: bicgstab.hxx:1
A::value_type dot(const A &a, const B &b)
Dot product of array or expression.
Definition: util.ixx:91
A::value_type norm(const A &a)
Euklidean norm of array or expression.
Definition: util.hxx:54