gegenbauer.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // (C) Copyright Nick Thompson 2019.
  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_SPECIAL_GEGENBAUER_HPP
  6. #define BOOST_MATH_SPECIAL_GEGENBAUER_HPP
  7. #include <limits>
  8. #include <stdexcept>
  9. #include <type_traits>
  10. namespace boost { namespace math {
  11. template<typename Real>
  12. Real gegenbauer(unsigned n, Real lambda, Real x)
  13. {
  14. static_assert(!std::is_integral<Real>::value, "Gegenbauer polynomials required floating point arguments.");
  15. if (lambda <= -1/Real(2)) {
  16. #ifndef BOOST_MATH_NO_EXCEPTIONS
  17. throw std::domain_error("lambda > -1/2 is required.");
  18. #else
  19. return std::numeric_limits<Real>::quiet_NaN();
  20. #endif
  21. }
  22. // The only reason to do this is because of some instability that could be present for x < 0 that is not present for x > 0.
  23. // I haven't observed this, but then again, I haven't managed to test an exhaustive number of parameters.
  24. // In any case, the routine is distinctly faster without this test:
  25. //if (x < 0) {
  26. // if (n&1) {
  27. // return -gegenbauer(n, lambda, -x);
  28. // }
  29. // return gegenbauer(n, lambda, -x);
  30. //}
  31. if (n == 0) {
  32. return Real(1);
  33. }
  34. Real y0 = 1;
  35. Real y1 = 2*lambda*x;
  36. Real yk = y1;
  37. Real k = 2;
  38. Real k_max = n*(1+std::numeric_limits<Real>::epsilon());
  39. Real gamma = 2*(lambda - 1);
  40. while(k < k_max)
  41. {
  42. yk = ( (2 + gamma/k)*x*y1 - (1+gamma/k)*y0);
  43. y0 = y1;
  44. y1 = yk;
  45. k += 1;
  46. }
  47. return yk;
  48. }
  49. template<typename Real>
  50. Real gegenbauer_derivative(unsigned n, Real lambda, Real x, unsigned k)
  51. {
  52. if (k > n) {
  53. return Real(0);
  54. }
  55. Real gegen = gegenbauer<Real>(n-k, lambda + k, x);
  56. Real scale = 1;
  57. for (unsigned j = 0; j < k; ++j) {
  58. scale *= 2*lambda;
  59. lambda += 1;
  60. }
  61. return scale*gegen;
  62. }
  63. template<typename Real>
  64. Real gegenbauer_prime(unsigned n, Real lambda, Real x) {
  65. return gegenbauer_derivative<Real>(n, lambda, x, 1);
  66. }
  67. }}
  68. #endif