cghs.hh 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // (c) Daniel Llorens - 2017
  2. // This library is free software; you can redistribute it and/or modify it under
  3. // the terms of the GNU Lesser General Public License as published by the Free
  4. // Software Foundation; either version 3 of the License, or (at your option) any
  5. // later version.
  6. /// @file cghs.cc
  7. /// @brief Conjugate gradient after Hestenes und Stiefel
  8. // Adapted from lsolver/cghs.cc by Christian Badura, 1998/05.
  9. #pragma once
  10. #include "ra/operators.hh"
  11. template <class A, class B, class X, class W>
  12. inline int
  13. cghs(A & a, B const & b, X & x, W & work, double eps)
  14. {
  15. work = 0.;
  16. auto g = work(0);
  17. auto r = work(1);
  18. auto p = work(2);
  19. double err = sqr(eps)*reduce_sqrm(b);
  20. mult(a, x, g);
  21. g = b-g;
  22. r = g;
  23. int i;
  24. for (i=0; reduce_sqrm(g)>err; ++i) {
  25. mult(a, r, p);
  26. double rho = reduce_sqrm(p);
  27. double sig = dot(r, p);
  28. double tau = dot(g, r);
  29. double t = tau/sig;
  30. double gam = (sqr(t)*rho-tau)/tau;
  31. x += t*r;
  32. g -= t*p;
  33. r = r*gam + g;
  34. }
  35. return i;
  36. }