cohen_acceleration.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // (C) Copyright Nick Thompson 2020.
  2. // Use, modification and distribution are subject to the
  3. // Boost Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_MATH_TOOLS_COHEN_ACCELERATION_HPP
  6. #define BOOST_MATH_TOOLS_COHEN_ACCELERATION_HPP
  7. #include <limits>
  8. #include <cmath>
  9. namespace boost::math::tools {
  10. // Algorithm 1 of https://people.mpim-bonn.mpg.de/zagier/files/exp-math-9/fulltext.pdf
  11. // Convergence Acceleration of Alternating Series: Henri Cohen, Fernando Rodriguez Villegas, and Don Zagier
  12. template<class G>
  13. auto cohen_acceleration(G& generator, int64_t n = -1)
  14. {
  15. using Real = decltype(generator());
  16. // This test doesn't pass for float128, sad!
  17. //static_assert(std::is_floating_point_v<Real>, "Real must be a floating point type.");
  18. using std::log;
  19. using std::pow;
  20. using std::ceil;
  21. using std::sqrt;
  22. Real n_ = n;
  23. if (n < 0)
  24. {
  25. // relative error grows as 2*5.828^-n; take 5.828^-n < eps/4 => -nln(5.828) < ln(eps/4) => n > ln(4/eps)/ln(5.828).
  26. // Is there a way to do it rapidly with std::log2? (Yes, of course; but for primitive types it's computed at compile-time anyway.)
  27. n_ = ceil(log(4/std::numeric_limits<Real>::epsilon())*0.5672963285532555);
  28. n = static_cast<int64_t>(n_);
  29. }
  30. // d can get huge and overflow if you pick n too large:
  31. Real d = pow(3 + sqrt(Real(8)), n);
  32. d = (d + 1/d)/2;
  33. Real b = -1;
  34. Real c = -d;
  35. Real s = 0;
  36. for (Real k = 0; k < n_; ++k) {
  37. c = b - c;
  38. s += c*generator();
  39. b = (k+n_)*(k-n_)*b/((k+Real(1)/Real(2))*(k+1));
  40. }
  41. return s/d;
  42. }
  43. }
  44. #endif