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