bessel_kn.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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,
  26. "Got x = %1%, but argument x must be non-negative, complex number result not supported.", x, pol);
  27. }
  28. if (x == 0)
  29. {
  30. return policies::raise_overflow_error<T>(function, 0, pol);
  31. }
  32. if (n < 0)
  33. {
  34. n = -n; // K_{-n}(z) = K_n(z)
  35. }
  36. if (n == 0)
  37. {
  38. value = bessel_k0(x);
  39. }
  40. else if (n == 1)
  41. {
  42. value = bessel_k1(x);
  43. }
  44. else
  45. {
  46. prev = bessel_k0(x);
  47. current = bessel_k1(x);
  48. int k = 1;
  49. BOOST_ASSERT(k < n);
  50. T scale = 1;
  51. do
  52. {
  53. T fact = 2 * k / x;
  54. if((tools::max_value<T>() - fabs(prev)) / fact < fabs(current))
  55. {
  56. scale /= current;
  57. prev /= current;
  58. current = 1;
  59. }
  60. value = fact * current + prev;
  61. prev = current;
  62. current = value;
  63. ++k;
  64. }
  65. while(k < n);
  66. if(tools::max_value<T>() * scale < fabs(value))
  67. return sign(scale) * sign(value) * policies::raise_overflow_error<T>(function, 0, pol);
  68. value /= scale;
  69. }
  70. return value;
  71. }
  72. }}} // namespaces
  73. #endif // BOOST_MATH_BESSEL_KN_HPP