bessel_kn.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright (c) 2006 Xiaogang Zhang
  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_BESSEL_KN_HPP
  6. #define BOOST_MATH_BESSEL_KN_HPP
  7. #ifdef _MSC_VER
  8. #pragma once
  9. #endif
  10. #include <boost/math/special_functions/detail/bessel_k0.hpp>
  11. #include <boost/math/special_functions/detail/bessel_k1.hpp>
  12. #include <boost/math/policies/error_handling.hpp>
  13. // Modified Bessel function of the second kind of integer order
  14. // K_n(z) is the dominant solution, forward recurrence always OK (though unstable)
  15. namespace boost { namespace math { namespace detail{
  16. template <typename T, typename Policy>
  17. T bessel_kn(int n, T x, const Policy& pol)
  18. {
  19. BOOST_MATH_STD_USING
  20. T value, current, prev;
  21. using namespace boost::math::tools;
  22. static const char* function = "boost::math::bessel_kn<%1%>(%1%,%1%)";
  23. if (x < 0)
  24. {
  25. return policies::raise_domain_error<T>(function, "Got x = %1%, but argument x must be non-negative, complex number result not supported.", x, pol);
  26. }
  27. if (x == 0)
  28. {
  29. return (n == 0) ?
  30. policies::raise_overflow_error<T>(function, nullptr, pol)
  31. : policies::raise_domain_error<T>(function, "Got x = %1%, but argument x must be positive, complex number result not supported.", x, pol);
  32. }
  33. if (n < 0)
  34. {
  35. n = -n; // K_{-n}(z) = K_n(z)
  36. }
  37. if (n == 0)
  38. {
  39. value = bessel_k0(x);
  40. }
  41. else if (n == 1)
  42. {
  43. value = bessel_k1(x);
  44. }
  45. else
  46. {
  47. prev = bessel_k0(x);
  48. current = bessel_k1(x);
  49. int k = 1;
  50. BOOST_MATH_ASSERT(k < n);
  51. T scale = 1;
  52. do
  53. {
  54. T fact = 2 * k / x;
  55. if((tools::max_value<T>() - fabs(prev)) / fact < fabs(current))
  56. {
  57. scale /= current;
  58. prev /= current;
  59. current = 1;
  60. }
  61. value = fact * current + prev;
  62. prev = current;
  63. current = value;
  64. ++k;
  65. }
  66. while(k < n);
  67. if (tools::max_value<T>() * scale < fabs(value))
  68. return ((boost::math::signbit)(scale) ? -1 : 1) * sign(value) * policies::raise_overflow_error<T>(function, nullptr, pol);
  69. value /= scale;
  70. }
  71. return value;
  72. }
  73. }}} // namespaces
  74. #endif // BOOST_MATH_BESSEL_KN_HPP