bessel_kn.hpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. T value, current, prev;
  20. using namespace boost::math::tools;
  21. static const char* function = "boost::math::bessel_kn<%1%>(%1%,%1%)";
  22. if (x < 0)
  23. {
  24. return policies::raise_domain_error<T>(function,
  25. "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 policies::raise_overflow_error<T>(function, 0, pol);
  30. }
  31. if (n < 0)
  32. {
  33. n = -n; // K_{-n}(z) = K_n(z)
  34. }
  35. if (n == 0)
  36. {
  37. value = bessel_k0(x, pol);
  38. }
  39. else if (n == 1)
  40. {
  41. value = bessel_k1(x, pol);
  42. }
  43. else
  44. {
  45. prev = bessel_k0(x, pol);
  46. current = bessel_k1(x, pol);
  47. int k = 1;
  48. BOOST_ASSERT(k < n);
  49. T scale = 1;
  50. do
  51. {
  52. T fact = 2 * k / x;
  53. if((tools::max_value<T>() - fabs(prev)) / fact < fabs(current))
  54. {
  55. scale /= current;
  56. prev /= current;
  57. current = 1;
  58. }
  59. value = fact * current + prev;
  60. prev = current;
  61. current = value;
  62. ++k;
  63. }
  64. while(k < n);
  65. if(tools::max_value<T>() * scale < fabs(value))
  66. return sign(scale) * sign(value) * policies::raise_overflow_error<T>(function, 0, pol);
  67. value /= scale;
  68. }
  69. return value;
  70. }
  71. }}} // namespaces
  72. #endif // BOOST_MATH_BESSEL_KN_HPP