powm1.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // (C) Copyright John Maddock 2006.
  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_POWM1
  6. #define BOOST_MATH_POWM1
  7. #ifdef _MSC_VER
  8. #pragma once
  9. #pragma warning(push)
  10. #pragma warning(disable:4702) // Unreachable code (release mode only warning)
  11. #endif
  12. #include <boost/math/special_functions/math_fwd.hpp>
  13. #include <boost/math/special_functions/log1p.hpp>
  14. #include <boost/math/special_functions/expm1.hpp>
  15. #include <boost/math/special_functions/trunc.hpp>
  16. #include <boost/assert.hpp>
  17. namespace boost{ namespace math{ namespace detail{
  18. template <class T, class Policy>
  19. inline T powm1_imp(const T x, const T y, const Policy& pol)
  20. {
  21. BOOST_MATH_STD_USING
  22. static const char* function = "boost::math::powm1<%1%>(%1%, %1%)";
  23. if (x > 0)
  24. {
  25. if ((fabs(y * (x - 1)) < 0.5) || (fabs(y) < 0.2))
  26. {
  27. // We don't have any good/quick approximation for log(x) * y
  28. // so just try it and see:
  29. T l = y * log(x);
  30. if (l < 0.5)
  31. return boost::math::expm1(l);
  32. if (l > boost::math::tools::log_max_value<T>())
  33. return boost::math::policies::raise_overflow_error<T>(function, 0, pol);
  34. // fall through....
  35. }
  36. }
  37. else
  38. {
  39. // y had better be an integer:
  40. if (boost::math::trunc(y) != y)
  41. return boost::math::policies::raise_domain_error<T>(function, "For non-integral exponent, expected base > 0 but got %1%", x, pol);
  42. if (boost::math::trunc(y / 2) == y / 2)
  43. return powm1_imp(T(-x), y, pol);
  44. }
  45. return pow(x, y) - 1;
  46. }
  47. } // detail
  48. template <class T1, class T2>
  49. inline typename tools::promote_args<T1, T2>::type
  50. powm1(const T1 a, const T2 z)
  51. {
  52. typedef typename tools::promote_args<T1, T2>::type result_type;
  53. return detail::powm1_imp(static_cast<result_type>(a), static_cast<result_type>(z), policies::policy<>());
  54. }
  55. template <class T1, class T2, class Policy>
  56. inline typename tools::promote_args<T1, T2>::type
  57. powm1(const T1 a, const T2 z, const Policy& pol)
  58. {
  59. typedef typename tools::promote_args<T1, T2>::type result_type;
  60. return detail::powm1_imp(static_cast<result_type>(a), static_cast<result_type>(z), pol);
  61. }
  62. } // namespace math
  63. } // namespace boost
  64. #ifdef _MSC_VER
  65. #pragma warning(pop)
  66. #endif
  67. #endif // BOOST_MATH_POWM1