bessel_kn.hpp 2.6 KB

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