powm1.hpp 2.2 KB

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