1 // Copyright John Maddock 2006-7.
2 // Copyright Paul A. Bristow 2007.
4 // Use, modification and distribution are subject to the
5 // Boost Software License, Version 1.0. (See accompanying file
6 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8 #ifndef BOOST_MATH_SF_GAMMA_HPP
9 #define BOOST_MATH_SF_GAMMA_HPP
15 #include <boost/config.hpp>
17 # pragma warning(push)
18 # pragma warning(disable: 4127 4701)
19 // // For lexical_cast, until fixed in 1.35?
20 // // conditional expression is constant &
21 // // Potentially uninitialized local variable 'name' used
23 #include <boost/lexical_cast.hpp>
27 #include <boost/math/tools/series.hpp>
28 #include <boost/math/tools/fraction.hpp>
29 #include <boost/math/tools/precision.hpp>
30 #include <boost/math/tools/promotion.hpp>
31 #include <boost/math/policies/error_handling.hpp>
32 #include <boost/math/constants/constants.hpp>
33 #include <boost/math/special_functions/math_fwd.hpp>
34 #include <boost/math/special_functions/log1p.hpp>
35 #include <boost/math/special_functions/trunc.hpp>
36 #include <boost/math/special_functions/powm1.hpp>
37 #include <boost/math/special_functions/sqrt1pm1.hpp>
38 #include <boost/math/special_functions/lanczos.hpp>
39 #include <boost/math/special_functions/fpclassify.hpp>
40 #include <boost/math/special_functions/detail/igamma_large.hpp>
41 #include <boost/math/special_functions/detail/unchecked_factorial.hpp>
42 #include <boost/math/special_functions/detail/lgamma_small.hpp>
43 #include <boost/type_traits/is_convertible.hpp>
44 #include <boost/assert.hpp>
45 #include <boost/mpl/greater.hpp>
46 #include <boost/mpl/equal_to.hpp>
47 #include <boost/mpl/greater.hpp>
49 #include <boost/config/no_tr1/cmath.hpp>
52 #ifdef BOOST_MATH_INSTRUMENT
59 # pragma warning(push)
60 # pragma warning(disable: 4702) // unreachable code (return after domain_error throw).
61 # pragma warning(disable: 4127) // conditional expression is constant.
62 # pragma warning(disable: 4100) // unreferenced formal parameter.
63 // Several variables made comments,
64 // but some difficulty as whether referenced on not may depend on macro values.
65 // So to be safe, 4100 warnings suppressed.
66 // TODO - revisit this?
69 namespace boost{ namespace math{
74 inline bool is_odd(T v, const boost::true_type&)
76 int i = static_cast<int>(v);
80 inline bool is_odd(T v, const boost::false_type&)
82 // Oh dear can't cast T to int!
84 T modulus = v - 2 * floor(v/2);
85 return static_cast<bool>(modulus != 0);
88 inline bool is_odd(T v)
90 return is_odd(v, ::boost::is_convertible<T, int>());
96 // Ad hoc function calculates x * sin(pi * x),
97 // taking extra care near when x is near a whole number.
120 BOOST_ASSERT(fl >= 0);
123 T result = sin(dist*boost::math::constants::pi<T>());
124 return sign*z*result;
125 } // template <class T> T sinpx(T z)
127 // tgamma(z), with Lanczos support:
129 template <class T, class Policy, class L>
130 T gamma_imp(T z, const Policy& pol, const L& l)
136 #ifdef BOOST_MATH_INSTRUMENT
137 static bool b = false;
140 std::cout << "tgamma_imp called with " << typeid(z).name() << " " << typeid(l).name() << std::endl;
144 static const char* function = "boost::math::tgamma<%1%>(%1%)";
149 return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
152 result = gamma_imp(T(-z), pol, l) * sinpx(z);
153 if((fabs(result) < 1) && (tools::max_value<T>() * fabs(result) < boost::math::constants::pi<T>()))
154 return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
155 result = -boost::math::constants::pi<T>() / result;
157 return policies::raise_underflow_error<T>(function, "Result of tgamma is too small to represent.", pol);
158 if((boost::math::fpclassify)(result) == (int)FP_SUBNORMAL)
159 return policies::raise_denorm_error<T>(function, "Result of tgamma is denormalized.", result, pol);
170 if((floor(z) == z) && (z < max_factorial<T>::value))
172 result *= unchecked_factorial<T>(itrunc(z, pol) - 1);
176 result *= L::lanczos_sum(z);
177 if(z * log(z) > tools::log_max_value<T>())
179 // we're going to overflow unless this is done with care:
180 T zgh = (z + static_cast<T>(L::g()) - boost::math::constants::half<T>());
181 if(log(zgh) * z / 2 > tools::log_max_value<T>())
182 return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
183 T hp = pow(zgh, (z / 2) - T(0.25));
184 result *= hp / exp(zgh);
185 if(tools::max_value<T>() / hp < result)
186 return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
191 T zgh = (z + static_cast<T>(L::g()) - boost::math::constants::half<T>());
192 result *= pow(zgh, z - boost::math::constants::half<T>()) / exp(zgh);
198 // lgamma(z) with Lanczos support:
200 template <class T, class Policy, class L>
201 T lgamma_imp(T z, const Policy& pol, const L& l, int* sign = 0)
203 #ifdef BOOST_MATH_INSTRUMENT
204 static bool b = false;
207 std::cout << "lgamma_imp called with " << typeid(z).name() << " " << typeid(l).name() << std::endl;
214 static const char* function = "boost::math::lgamma<%1%>(%1%)";
220 // reflection formula:
222 return policies::raise_pole_error<T>(function, "Evaluation of lgamma at a negative integer %1%.", z, pol);
234 result = log(boost::math::constants::pi<T>()) - lgamma_imp(z, pol, l) - log(t);
238 typedef typename policies::precision<T, Policy>::type precision_type;
239 typedef typename mpl::if_<
241 mpl::less_equal<precision_type, mpl::int_<64> >,
242 mpl::greater<precision_type, mpl::int_<0> >
247 mpl::less_equal<precision_type, mpl::int_<113> >,
248 mpl::greater<precision_type, mpl::int_<0> >
250 mpl::int_<113>, mpl::int_<0> >::type
252 result = lgamma_small_imp<T>(z, z - 1, z - 2, tag_type(), pol, l);
254 else if((z >= 3) && (z < 100))
256 // taking the log of tgamma reduces the error, no danger of overflow here:
257 result = log(gamma_imp(z, pol, l));
261 // regular evaluation:
262 T zgh = static_cast<T>(z + L::g() - boost::math::constants::half<T>());
263 result = log(zgh) - 1;
265 result += log(L::lanczos_sum_expG_scaled(z));
274 // Incomplete gamma functions follow:
277 struct upper_incomplete_gamma_fract
283 typedef std::pair<T,T> result_type;
285 upper_incomplete_gamma_fract(T a1, T z1)
286 : z(z1-a1+1), a(a1), k(0)
290 result_type operator()()
294 return result_type(k * (a - k), z);
299 inline T upper_gamma_fraction(T a, T z, T eps)
301 // Multiply result by z^a * e^-z to get the full
302 // upper incomplete integral. Divide by tgamma(z)
304 upper_incomplete_gamma_fract<T> f(a, z);
305 return 1 / (z - a + 1 + boost::math::tools::continued_fraction_a(f, eps));
309 struct lower_incomplete_gamma_series
314 typedef T result_type;
315 lower_incomplete_gamma_series(T a1, T z1) : a(a1), z(z1), result(1){}
326 template <class T, class Policy>
327 inline T lower_gamma_series(T a, T z, const Policy& pol, T init_value = 0)
329 // Multiply result by ((z^a) * (e^-z) / a) to get the full
330 // lower incomplete integral. Then divide by tgamma(a)
331 // to get the normalised value.
332 lower_incomplete_gamma_series<T> s(a, z);
333 boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
334 T factor = policies::get_epsilon<T, Policy>();
335 T result = boost::math::tools::sum_series(s, factor, max_iter, init_value);
336 policies::check_series_iterations("boost::math::detail::lower_gamma_series<%1%>(%1%)", max_iter, pol);
341 // Fully generic tgamma and lgamma use the incomplete partial
342 // sums added together:
344 template <class T, class Policy>
345 T gamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos& l)
347 static const char* function = "boost::math::tgamma<%1%>(%1%)";
349 if((z <= 0) && (floor(z) == z))
350 return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
353 T result = gamma_imp(-z, pol, l) * sinpx(z);
354 if((fabs(result) < 1) && (tools::max_value<T>() * fabs(result) < boost::math::constants::pi<T>()))
355 return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
356 result = -boost::math::constants::pi<T>() / result;
358 return policies::raise_underflow_error<T>(function, "Result of tgamma is too small to represent.", pol);
359 if((boost::math::fpclassify)(result) == (int)FP_SUBNORMAL)
360 return policies::raise_denorm_error<T>(function, "Result of tgamma is denormalized.", result, pol);
364 // The upper gamma fraction is *very* slow for z < 6, actually it's very
365 // slow to converge everywhere but recursing until z > 6 gets rid of the
366 // worst of it's behaviour.
374 BOOST_MATH_INSTRUMENT_CODE(prefix);
375 if((floor(z) == z) && (z < max_factorial<T>::value))
377 prefix *= unchecked_factorial<T>(itrunc(z, pol) - 1);
381 prefix = prefix * pow(z / boost::math::constants::e<T>(), z);
382 BOOST_MATH_INSTRUMENT_CODE(prefix);
383 T sum = detail::lower_gamma_series(z, z, pol) / z;
384 BOOST_MATH_INSTRUMENT_CODE(sum);
385 sum += detail::upper_gamma_fraction(z, z, ::boost::math::policies::get_epsilon<T, Policy>());
386 BOOST_MATH_INSTRUMENT_CODE(sum);
387 if(fabs(tools::max_value<T>() / prefix) < fabs(sum))
388 return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
389 BOOST_MATH_INSTRUMENT_CODE((sum * prefix));
395 template <class T, class Policy>
396 T lgamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos& l, int*sign)
400 static const char* function = "boost::math::lgamma<%1%>(%1%)";
406 return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
407 T t = detail::sinpx(z);
417 result = log(boost::math::constants::pi<T>()) - lgamma_imp(z, pol, l, 0) - log(t);
419 else if((z != 1) && (z != 2))
421 T limit = (std::max)(z+1, T(10));
422 T prefix = z * log(limit) - limit;
423 T sum = detail::lower_gamma_series(z, limit, pol) / z;
424 sum += detail::upper_gamma_fraction(z, limit, ::boost::math::policies::get_epsilon<T, Policy>());
425 result = log(sum) + prefix;
432 // This helper calculates tgamma(dz+1)-1 without cancellation errors,
433 // used by the upper incomplete gamma with z < 1:
435 template <class T, class Policy, class L>
436 T tgammap1m1_imp(T dz, Policy const& pol, const L& l)
440 typedef typename policies::precision<T,Policy>::type precision_type;
442 typedef typename mpl::if_<
444 mpl::less_equal<precision_type, mpl::int_<0> >,
445 mpl::greater<precision_type, mpl::int_<113> >
448 is_same<L, lanczos::lanczos24m113>,
453 mpl::less_equal<precision_type, mpl::int_<64> >,
454 mpl::int_<64>, mpl::int_<113> >::type
462 // Best method is simply to subtract 1 from tgamma:
463 result = boost::math::tgamma(1+dz, pol) - 1;
464 BOOST_MATH_INSTRUMENT_CODE(result);
468 // Use expm1 on lgamma:
469 result = boost::math::expm1(-boost::math::log1p(dz, pol)
470 + lgamma_small_imp<T>(dz+2, dz + 1, dz, tag_type(), pol, l));
471 BOOST_MATH_INSTRUMENT_CODE(result);
478 // Use expm1 on lgamma:
479 result = boost::math::expm1(lgamma_small_imp<T>(dz+1, dz, dz-1, tag_type(), pol, l), pol);
480 BOOST_MATH_INSTRUMENT_CODE(result);
484 // Best method is simply to subtract 1 from tgamma:
485 result = boost::math::tgamma(1+dz, pol) - 1;
486 BOOST_MATH_INSTRUMENT_CODE(result);
493 template <class T, class Policy>
494 inline T tgammap1m1_imp(T dz, Policy const& pol,
495 const ::boost::math::lanczos::undefined_lanczos& l)
497 BOOST_MATH_STD_USING // ADL of std names
499 // There should be a better solution than this, but the
500 // algebra isn't easy for the general case....
501 // Start by subracting 1 from tgamma:
503 T result = gamma_imp(1 + dz, pol, l) - 1;
504 BOOST_MATH_INSTRUMENT_CODE(result);
506 // Test the level of cancellation error observed: we loose one bit
507 // for each power of 2 the result is less than 1. If we would get
508 // more bits from our most precise lgamma rational approximation,
509 // then use that instead:
511 BOOST_MATH_INSTRUMENT_CODE((dz > -0.5));
512 BOOST_MATH_INSTRUMENT_CODE((dz < 2));
513 BOOST_MATH_INSTRUMENT_CODE((ldexp(1.0, boost::math::policies::digits<T, Policy>()) * fabs(result) < 1e34));
514 if((dz > -0.5) && (dz < 2) && (ldexp(1.0, boost::math::policies::digits<T, Policy>()) * fabs(result) < 1e34))
516 result = tgammap1m1_imp(dz, pol, boost::math::lanczos::lanczos24m113());
517 BOOST_MATH_INSTRUMENT_CODE(result);
523 // Series representation for upper fraction when z is small:
526 struct small_gamma2_series
528 typedef T result_type;
530 small_gamma2_series(T a_, T x_) : result(-x_), x(-x_), apn(a_+1), n(1){}
534 T r = result / (apn);
546 // calculate power term prefix (z^a)(e^-z) used in the non-normalised
547 // incomplete gammas:
549 template <class T, class Policy>
550 T full_igamma_prefix(T a, T z, const Policy& pol)
559 if((alz < tools::log_max_value<T>()) && (-z > tools::log_min_value<T>()))
561 prefix = pow(z, a) * exp(-z);
565 prefix = pow(z / exp(z/a), a);
569 prefix = exp(alz - z);
574 if(alz > tools::log_min_value<T>())
576 prefix = pow(z, a) * exp(-z);
578 else if(z/a < tools::log_max_value<T>())
580 prefix = pow(z / exp(z/a), a);
584 prefix = exp(alz - z);
588 // This error handling isn't very good: it happens after the fact
589 // rather than before it...
591 if((boost::math::fpclassify)(prefix) == (int)FP_INFINITE)
592 policies::raise_overflow_error<T>("boost::math::detail::full_igamma_prefix<%1%>(%1%, %1%)", "Result of incomplete gamma function is too large to represent.", pol);
597 // Compute (z^a)(e^-z)/tgamma(a)
598 // most if the error occurs in this function:
600 template <class T, class Policy, class L>
601 T regularised_gamma_prefix(T a, T z, const Policy& pol, const L& l)
604 T agh = a + static_cast<T>(L::g()) - T(0.5);
606 T d = ((z - a) - static_cast<T>(L::g()) + T(0.5)) / agh;
611 // We have to treat a < 1 as a special case because our Lanczos
612 // approximations are optimised against the factorials with a > 1,
613 // and for high precision types especially (128-bit reals for example)
614 // very small values of a can give rather eroneous results for gamma
615 // unless we do this:
617 // TODO: is this still required? Lanczos approx should be better now?
619 if(z <= tools::log_min_value<T>())
621 // Oh dear, have to use logs, should be free of cancellation errors though:
622 return exp(a * log(z) - z - lgamma_imp(a, pol, l));
626 // direct calculation, no danger of overflow as gamma(a) < 1/a
628 return pow(z, a) * exp(-z) / gamma_imp(a, pol, l);
631 else if((fabs(d*d*a) <= 100) && (a > 150))
633 // special case for large a and a ~ z.
634 prefix = a * boost::math::log1pmx(d, pol) + z * static_cast<T>(0.5 - L::g()) / agh;
635 prefix = exp(prefix);
641 // direct computation is most accurate, but use various fallbacks
642 // for different parts of the problem domain:
644 T alz = a * log(z / agh);
646 if(((std::min)(alz, amz) <= tools::log_min_value<T>()) || ((std::max)(alz, amz) >= tools::log_max_value<T>()))
649 if(((std::min)(alz, amz)/2 > tools::log_min_value<T>()) && ((std::max)(alz, amz)/2 < tools::log_max_value<T>()))
651 // compute square root of the result and then square it:
652 T sq = pow(z / agh, a / 2) * exp(amz / 2);
655 else if(((std::min)(alz, amz)/4 > tools::log_min_value<T>()) && ((std::max)(alz, amz)/4 < tools::log_max_value<T>()) && (z > a))
657 // compute the 4th root of the result then square it twice:
658 T sq = pow(z / agh, a / 4) * exp(amz / 4);
662 else if((amza > tools::log_min_value<T>()) && (amza < tools::log_max_value<T>()))
664 prefix = pow((z * exp(amza)) / agh, a);
668 prefix = exp(alz + amz);
673 prefix = pow(z / agh, a) * exp(amz);
676 prefix *= sqrt(agh / boost::math::constants::e<T>()) / L::lanczos_sum_expG_scaled(a);
680 // And again, without Lanczos support:
682 template <class T, class Policy>
683 T regularised_gamma_prefix(T a, T z, const Policy& pol, const lanczos::undefined_lanczos&)
687 T limit = (std::max)(T(10), a);
688 T sum = detail::lower_gamma_series(a, limit, pol) / a;
689 sum += detail::upper_gamma_fraction(a, limit, ::boost::math::policies::get_epsilon<T, Policy>());
693 // special case for small a:
694 T prefix = pow(z / 10, a);
698 prefix = pow((z * exp((10-z)/a)) / 10, a);
706 T alzoa = a * log(zoa);
708 if(((std::min)(alzoa, amz) <= tools::log_min_value<T>()) || ((std::max)(alzoa, amz) >= tools::log_max_value<T>()))
711 if((amza <= tools::log_min_value<T>()) || (amza >= tools::log_max_value<T>()))
713 prefix = exp(alzoa + amz);
717 prefix = pow(zoa * exp(amza), a);
722 prefix = pow(zoa, a) * exp(amz);
728 // Upper gamma fraction for very small a:
730 template <class T, class Policy>
731 inline T tgamma_small_upper_part(T a, T x, const Policy& pol, T* pgam = 0, bool invert = false, T* pderivative = 0)
733 BOOST_MATH_STD_USING // ADL of std functions.
735 // Compute the full upper fraction (Q) when a is very small:
738 result = boost::math::tgamma1pm1(a, pol);
740 *pgam = (result + 1) / a;
741 T p = boost::math::powm1(x, a, pol);
744 detail::small_gamma2_series<T> s(a, x);
745 boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>() - 10;
748 *pderivative = p / (*pgam * exp(x));
749 T init_value = invert ? *pgam : 0;
750 result = -p * tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, (init_value - result) / p);
751 policies::check_series_iterations("boost::math::tgamma_small_upper_part<%1%>(%1%, %1%)", max_iter, pol);
757 // Upper gamma fraction for integer a:
759 template <class T, class Policy>
760 inline T finite_gamma_q(T a, T x, Policy const& pol, T* pderivative = 0)
763 // Calculates normalised Q when a is an integer:
771 for(unsigned n = 1; n < a; ++n)
780 *pderivative = e * pow(x, a) / boost::math::unchecked_factorial<T>(itrunc(T(a - 1), pol));
785 // Upper gamma fraction for half integer a:
787 template <class T, class Policy>
788 T finite_half_gamma_q(T a, T x, T* p_derivative, const Policy& pol)
791 // Calculates normalised Q when a is a half-integer:
794 T e = boost::math::erfc(sqrt(x), pol);
795 if((e != 0) && (a > 1))
797 T term = exp(-x) / sqrt(constants::pi<T>() * x);
799 static const T half = T(1) / 2;
802 for(unsigned n = 2; n < a; ++n)
814 else if(p_derivative)
816 // We'll be dividing by x later, so calculate derivative * x:
817 *p_derivative = sqrt(x) * exp(-x) / constants::root_pi<T>();
822 // Main incomplete gamma entry point, handles all four incomplete gamma's:
824 template <class T, class Policy>
825 T gamma_incomplete_imp(T a, T x, bool normalised, bool invert,
826 const Policy& pol, T* p_derivative)
828 static const char* function = "boost::math::gamma_p<%1%>(%1%, %1%)";
830 policies::raise_domain_error<T>(function, "Argument a to the incomplete gamma function must be greater than zero (got a=%1%).", a, pol);
832 policies::raise_domain_error<T>(function, "Argument x to the incomplete gamma function must be >= 0 (got x=%1%).", x, pol);
836 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
840 BOOST_ASSERT((p_derivative == 0) || (normalised == true));
842 bool is_int, is_half_int;
843 bool is_small_a = (a < 30) && (a <= x + 1);
848 is_half_int = is_int ? false : (fabs(fa - a) == 0.5f);
852 is_int = is_half_int = false;
857 if(is_int && (x > 0.6))
859 // calculate Q via finite sum:
863 else if(is_half_int && (x > 0.2))
865 // calculate Q via finite sum for half integer a:
872 // Changeover criterion chosen to give a changeover at Q ~ 0.33
874 if(-0.4 / log(x) < a)
886 // Changover here occurs when P ~ 0.75 or Q ~ 0.25:
900 // Begin by testing whether we're in the "bad" zone
901 // where the result will be near 0.5 and the usual
902 // series and continued fractions are slow to converge:
904 bool use_temme = false;
905 if(normalised && std::numeric_limits<T>::is_specialized && (a > 20))
907 T sigma = fabs((x-a)/a);
908 if((a > 200) && (policies::digits<T, Policy>() <= 113))
911 // This limit is chosen so that we use Temme's expansion
912 // only if the result would be larger than about 10^-6.
913 // Below that the regular series and continued fractions
914 // converge OK, and if we use Temme's method we get increasing
915 // errors from the dominant erfc term as it's (inexact) argument
916 // increases in magnitude.
918 if(20 / a > sigma * sigma)
921 else if(policies::digits<T, Policy>() <= 64)
923 // Note in this zone we can't use Temme's expansion for
924 // types longer than an 80-bit real:
925 // it would require too many terms in the polynomials.
937 // Regular case where the result will not be too close to 0.5.
939 // Changeover here occurs at P ~ Q ~ 0.5
940 // Note that series computation of P is about x2 faster than continued fraction
941 // calculation of Q, so try and use the CF only when really necessary, especially
944 if(x - (1 / (3 * x)) < a)
960 result = finite_gamma_q(a, x, pol, p_derivative);
961 if(normalised == false)
962 result *= boost::math::tgamma(a, pol);
967 result = finite_half_gamma_q(a, x, p_derivative, pol);
968 if(normalised == false)
969 result *= boost::math::tgamma(a, pol);
970 if(p_derivative && (*p_derivative == 0))
971 *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
977 result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
979 *p_derivative = result;
985 init_value = -a * (normalised ? 1 : boost::math::tgamma(a, pol)) / result;
987 result *= detail::lower_gamma_series(a, x, pol, init_value) / a;
1001 result = tgamma_small_upper_part(a, x, pol, &g, invert, p_derivative);
1010 result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
1012 *p_derivative = result;
1014 result *= upper_gamma_fraction(a, x, policies::get_epsilon<T, Policy>());
1020 // Use compile time dispatch to the appropriate
1021 // Temme asymptotic expansion. This may be dead code
1022 // if T does not have numeric limits support, or has
1023 // too many digits for the most precise version of
1024 // these expansions, in that case we'll be calling
1025 // an empty function.
1027 typedef typename policies::precision<T, Policy>::type precision_type;
1029 typedef typename mpl::if_<
1030 mpl::or_<mpl::equal_to<precision_type, mpl::int_<0> >,
1031 mpl::greater<precision_type, mpl::int_<113> > >,
1034 mpl::less_equal<precision_type, mpl::int_<53> >,
1037 mpl::less_equal<precision_type, mpl::int_<64> >,
1044 result = igamma_temme_large(a, x, pol, static_cast<tag_type const*>(0));
1048 *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
1053 if(normalised && (result > 1))
1057 T gam = normalised ? 1 : boost::math::tgamma(a, pol);
1058 result = gam - result;
1063 // Need to convert prefix term to derivative:
1065 if((x < 1) && (tools::max_value<T>() * x < *p_derivative))
1067 // overflow, just return an arbitrarily large value:
1068 *p_derivative = tools::max_value<T>() / 2;
1078 // Ratios of two gamma functions:
1080 template <class T, class Policy, class L>
1081 T tgamma_delta_ratio_imp_lanczos(T z, T delta, const Policy& pol, const L&)
1083 BOOST_MATH_STD_USING
1084 T zgh = z + L::g() - constants::half<T>();
1086 if(fabs(delta) < 10)
1088 result = exp((constants::half<T>() - z) * boost::math::log1p(delta / zgh, pol));
1092 result = pow(zgh / (zgh + delta), z - constants::half<T>());
1094 result *= pow(constants::e<T>() / (zgh + delta), delta);
1095 result *= L::lanczos_sum(z) / L::lanczos_sum(z + delta);
1099 // And again without Lanczos support this time:
1101 template <class T, class Policy>
1102 T tgamma_delta_ratio_imp_lanczos(T z, T delta, const Policy& pol, const lanczos::undefined_lanczos&)
1104 BOOST_MATH_STD_USING
1106 // The upper gamma fraction is *very* slow for z < 6, actually it's very
1107 // slow to converge everywhere but recursing until z > 6 gets rid of the
1108 // worst of it's behaviour.
1112 while((zd < 6) && (z < 6))
1121 prefix *= exp(-z * boost::math::log1p(delta / z, pol));
1125 prefix *= pow(z / zd, z);
1127 prefix *= pow(constants::e<T>() / zd, delta);
1128 T sum = detail::lower_gamma_series(z, z, pol) / z;
1129 sum += detail::upper_gamma_fraction(z, z, ::boost::math::policies::get_epsilon<T, Policy>());
1130 T sumd = detail::lower_gamma_series(zd, zd, pol) / zd;
1131 sumd += detail::upper_gamma_fraction(zd, zd, ::boost::math::policies::get_epsilon<T, Policy>());
1133 if(fabs(tools::max_value<T>() / prefix) < fabs(sum))
1134 return policies::raise_overflow_error<T>("boost::math::tgamma_delta_ratio<%1%>(%1%, %1%)", "Result of tgamma is too large to represent.", pol);
1135 return sum * prefix;
1138 template <class T, class Policy>
1139 T tgamma_delta_ratio_imp(T z, T delta, const Policy& pol)
1141 BOOST_MATH_STD_USING
1144 policies::raise_domain_error<T>("boost::math::tgamma_delta_ratio<%1%>(%1%, %1%)", "Gamma function ratios only implemented for positive arguments (got a=%1%).", z, pol);
1146 policies::raise_domain_error<T>("boost::math::tgamma_delta_ratio<%1%>(%1%, %1%)", "Gamma function ratios only implemented for positive arguments (got b=%1%).", z+delta, pol);
1148 if(floor(delta) == delta)
1153 // Both z and delta are integers, see if we can just use table lookup
1154 // of the factorials to get the result:
1156 if((z <= max_factorial<T>::value) && (z + delta <= max_factorial<T>::value))
1158 return unchecked_factorial<T>((unsigned)itrunc(z, pol) - 1) / unchecked_factorial<T>((unsigned)itrunc(T(z + delta), pol) - 1);
1161 if(fabs(delta) < 20)
1164 // delta is a small integer, we can use a finite product:
1172 while(0 != (delta += 1))
1182 while(0 != (delta -= 1))
1191 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
1192 return tgamma_delta_ratio_imp_lanczos(z, delta, pol, lanczos_type());
1195 template <class T, class Policy>
1196 T gamma_p_derivative_imp(T a, T x, const Policy& pol)
1199 // Usual error checks first:
1202 policies::raise_domain_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", "Argument a to the incomplete gamma function must be greater than zero (got a=%1%).", a, pol);
1204 policies::raise_domain_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", "Argument x to the incomplete gamma function must be >= 0 (got x=%1%).", x, pol);
1206 // Now special cases:
1210 return (a > 1) ? 0 :
1211 (a == 1) ? 1 : policies::raise_overflow_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", 0, pol);
1216 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
1217 T f1 = detail::regularised_gamma_prefix(a, x, pol, lanczos_type());
1218 if((x < 1) && (tools::max_value<T>() * x < f1))
1221 return policies::raise_overflow_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", 0, pol);
1229 template <class T, class Policy>
1230 inline typename tools::promote_args<T>::type
1231 tgamma(T z, const Policy& /* pol */, const mpl::true_)
1233 BOOST_FPU_EXCEPTION_GUARD
1234 typedef typename tools::promote_args<T>::type result_type;
1235 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1236 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1237 typedef typename policies::normalise<
1239 policies::promote_float<false>,
1240 policies::promote_double<false>,
1241 policies::discrete_quantile<>,
1242 policies::assert_undefined<> >::type forwarding_policy;
1243 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::gamma_imp(static_cast<value_type>(z), forwarding_policy(), evaluation_type()), "boost::math::tgamma<%1%>(%1%)");
1246 template <class T1, class T2, class Policy>
1247 inline typename tools::promote_args<T1, T2>::type
1248 tgamma(T1 a, T2 z, const Policy&, const mpl::false_)
1250 BOOST_FPU_EXCEPTION_GUARD
1251 typedef typename tools::promote_args<T1, T2>::type result_type;
1252 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1253 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1254 typedef typename policies::normalise<
1256 policies::promote_float<false>,
1257 policies::promote_double<false>,
1258 policies::discrete_quantile<>,
1259 policies::assert_undefined<> >::type forwarding_policy;
1260 return policies::checked_narrowing_cast<result_type, forwarding_policy>(
1261 detail::gamma_incomplete_imp(static_cast<value_type>(a),
1262 static_cast<value_type>(z), false, true,
1263 forwarding_policy(), static_cast<value_type*>(0)), "boost::math::tgamma<%1%>(%1%, %1%)");
1266 template <class T1, class T2>
1267 inline typename tools::promote_args<T1, T2>::type
1268 tgamma(T1 a, T2 z, const mpl::false_ tag)
1270 return tgamma(a, z, policies::policy<>(), tag);
1273 } // namespace detail
1276 inline typename tools::promote_args<T>::type
1279 return tgamma(z, policies::policy<>());
1282 template <class T, class Policy>
1283 inline typename tools::promote_args<T>::type
1284 lgamma(T z, int* sign, const Policy&)
1286 BOOST_FPU_EXCEPTION_GUARD
1287 typedef typename tools::promote_args<T>::type result_type;
1288 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1289 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1290 typedef typename policies::normalise<
1292 policies::promote_float<false>,
1293 policies::promote_double<false>,
1294 policies::discrete_quantile<>,
1295 policies::assert_undefined<> >::type forwarding_policy;
1296 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::lgamma_imp(static_cast<value_type>(z), forwarding_policy(), evaluation_type(), sign), "boost::math::lgamma<%1%>(%1%)");
1300 inline typename tools::promote_args<T>::type
1301 lgamma(T z, int* sign)
1303 return lgamma(z, sign, policies::policy<>());
1306 template <class T, class Policy>
1307 inline typename tools::promote_args<T>::type
1308 lgamma(T x, const Policy& pol)
1310 return ::boost::math::lgamma(x, 0, pol);
1314 inline typename tools::promote_args<T>::type
1317 return ::boost::math::lgamma(x, 0, policies::policy<>());
1320 template <class T, class Policy>
1321 inline typename tools::promote_args<T>::type
1322 tgamma1pm1(T z, const Policy& /* pol */)
1324 BOOST_FPU_EXCEPTION_GUARD
1325 typedef typename tools::promote_args<T>::type result_type;
1326 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1327 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1328 typedef typename policies::normalise<
1330 policies::promote_float<false>,
1331 policies::promote_double<false>,
1332 policies::discrete_quantile<>,
1333 policies::assert_undefined<> >::type forwarding_policy;
1335 return policies::checked_narrowing_cast<typename remove_cv<result_type>::type, forwarding_policy>(detail::tgammap1m1_imp(static_cast<value_type>(z), forwarding_policy(), evaluation_type()), "boost::math::tgamma1pm1<%!%>(%1%)");
1339 inline typename tools::promote_args<T>::type
1342 return tgamma1pm1(z, policies::policy<>());
1346 // Full upper incomplete gamma:
1348 template <class T1, class T2>
1349 inline typename tools::promote_args<T1, T2>::type
1353 // Type T2 could be a policy object, or a value, select the
1354 // right overload based on T2:
1356 typedef typename policies::is_policy<T2>::type maybe_policy;
1357 return detail::tgamma(a, z, maybe_policy());
1359 template <class T1, class T2, class Policy>
1360 inline typename tools::promote_args<T1, T2>::type
1361 tgamma(T1 a, T2 z, const Policy& pol)
1363 return detail::tgamma(a, z, pol, mpl::false_());
1366 // Full lower incomplete gamma:
1368 template <class T1, class T2, class Policy>
1369 inline typename tools::promote_args<T1, T2>::type
1370 tgamma_lower(T1 a, T2 z, const Policy&)
1372 BOOST_FPU_EXCEPTION_GUARD
1373 typedef typename tools::promote_args<T1, T2>::type result_type;
1374 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1375 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1376 typedef typename policies::normalise<
1378 policies::promote_float<false>,
1379 policies::promote_double<false>,
1380 policies::discrete_quantile<>,
1381 policies::assert_undefined<> >::type forwarding_policy;
1383 return policies::checked_narrowing_cast<result_type, forwarding_policy>(
1384 detail::gamma_incomplete_imp(static_cast<value_type>(a),
1385 static_cast<value_type>(z), false, false,
1386 forwarding_policy(), static_cast<value_type*>(0)), "tgamma_lower<%1%>(%1%, %1%)");
1388 template <class T1, class T2>
1389 inline typename tools::promote_args<T1, T2>::type
1390 tgamma_lower(T1 a, T2 z)
1392 return tgamma_lower(a, z, policies::policy<>());
1395 // Regularised upper incomplete gamma:
1397 template <class T1, class T2, class Policy>
1398 inline typename tools::promote_args<T1, T2>::type
1399 gamma_q(T1 a, T2 z, const Policy& /* pol */)
1401 BOOST_FPU_EXCEPTION_GUARD
1402 typedef typename tools::promote_args<T1, T2>::type result_type;
1403 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1404 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1405 typedef typename policies::normalise<
1407 policies::promote_float<false>,
1408 policies::promote_double<false>,
1409 policies::discrete_quantile<>,
1410 policies::assert_undefined<> >::type forwarding_policy;
1412 return policies::checked_narrowing_cast<result_type, forwarding_policy>(
1413 detail::gamma_incomplete_imp(static_cast<value_type>(a),
1414 static_cast<value_type>(z), true, true,
1415 forwarding_policy(), static_cast<value_type*>(0)), "gamma_q<%1%>(%1%, %1%)");
1417 template <class T1, class T2>
1418 inline typename tools::promote_args<T1, T2>::type
1421 return gamma_q(a, z, policies::policy<>());
1424 // Regularised lower incomplete gamma:
1426 template <class T1, class T2, class Policy>
1427 inline typename tools::promote_args<T1, T2>::type
1428 gamma_p(T1 a, T2 z, const Policy&)
1430 BOOST_FPU_EXCEPTION_GUARD
1431 typedef typename tools::promote_args<T1, T2>::type result_type;
1432 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1433 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1434 typedef typename policies::normalise<
1436 policies::promote_float<false>,
1437 policies::promote_double<false>,
1438 policies::discrete_quantile<>,
1439 policies::assert_undefined<> >::type forwarding_policy;
1441 return policies::checked_narrowing_cast<result_type, forwarding_policy>(
1442 detail::gamma_incomplete_imp(static_cast<value_type>(a),
1443 static_cast<value_type>(z), true, false,
1444 forwarding_policy(), static_cast<value_type*>(0)), "gamma_p<%1%>(%1%, %1%)");
1446 template <class T1, class T2>
1447 inline typename tools::promote_args<T1, T2>::type
1450 return gamma_p(a, z, policies::policy<>());
1453 // ratios of gamma functions:
1454 template <class T1, class T2, class Policy>
1455 inline typename tools::promote_args<T1, T2>::type
1456 tgamma_delta_ratio(T1 z, T2 delta, const Policy& /* pol */)
1458 BOOST_FPU_EXCEPTION_GUARD
1459 typedef typename tools::promote_args<T1, T2>::type result_type;
1460 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1461 typedef typename policies::normalise<
1463 policies::promote_float<false>,
1464 policies::promote_double<false>,
1465 policies::discrete_quantile<>,
1466 policies::assert_undefined<> >::type forwarding_policy;
1468 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::tgamma_delta_ratio_imp(static_cast<value_type>(z), static_cast<value_type>(delta), forwarding_policy()), "boost::math::tgamma_delta_ratio<%1%>(%1%, %1%)");
1470 template <class T1, class T2>
1471 inline typename tools::promote_args<T1, T2>::type
1472 tgamma_delta_ratio(T1 z, T2 delta)
1474 return tgamma_delta_ratio(z, delta, policies::policy<>());
1476 template <class T1, class T2, class Policy>
1477 inline typename tools::promote_args<T1, T2>::type
1478 tgamma_ratio(T1 a, T2 b, const Policy&)
1480 typedef typename tools::promote_args<T1, T2>::type result_type;
1481 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1482 typedef typename policies::normalise<
1484 policies::promote_float<false>,
1485 policies::promote_double<false>,
1486 policies::discrete_quantile<>,
1487 policies::assert_undefined<> >::type forwarding_policy;
1489 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::tgamma_delta_ratio_imp(static_cast<value_type>(a), static_cast<value_type>(static_cast<value_type>(b) - static_cast<value_type>(a)), forwarding_policy()), "boost::math::tgamma_delta_ratio<%1%>(%1%, %1%)");
1491 template <class T1, class T2>
1492 inline typename tools::promote_args<T1, T2>::type
1493 tgamma_ratio(T1 a, T2 b)
1495 return tgamma_ratio(a, b, policies::policy<>());
1498 template <class T1, class T2, class Policy>
1499 inline typename tools::promote_args<T1, T2>::type
1500 gamma_p_derivative(T1 a, T2 x, const Policy&)
1502 BOOST_FPU_EXCEPTION_GUARD
1503 typedef typename tools::promote_args<T1, T2>::type result_type;
1504 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1505 typedef typename policies::normalise<
1507 policies::promote_float<false>,
1508 policies::promote_double<false>,
1509 policies::discrete_quantile<>,
1510 policies::assert_undefined<> >::type forwarding_policy;
1512 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::gamma_p_derivative_imp(static_cast<value_type>(a), static_cast<value_type>(x), forwarding_policy()), "boost::math::gamma_p_derivative<%1%>(%1%, %1%)");
1514 template <class T1, class T2>
1515 inline typename tools::promote_args<T1, T2>::type
1516 gamma_p_derivative(T1 a, T2 x)
1518 return gamma_p_derivative(a, x, policies::policy<>());
1522 } // namespace boost
1525 # pragma warning(pop)
1528 #include <boost/math/special_functions/detail/igamma_inverse.hpp>
1529 #include <boost/math/special_functions/detail/gamma_inva.hpp>
1530 #include <boost/math/special_functions/erf.hpp>
1532 #endif // BOOST_MATH_SF_GAMMA_HPP