2 // Copyright John Maddock 2006-7, 2013-14.
3 // Copyright Paul A. Bristow 2007, 2013-14.
4 // Copyright Nikhar Agrawal 2013-14
5 // Copyright Christopher Kormanyos 2013-14
7 // Use, modification and distribution are subject to the
8 // Boost Software License, Version 1.0. (See accompanying file
9 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
11 #ifndef BOOST_MATH_SF_GAMMA_HPP
12 #define BOOST_MATH_SF_GAMMA_HPP
18 #include <boost/config.hpp>
19 #include <boost/math/tools/series.hpp>
20 #include <boost/math/tools/fraction.hpp>
21 #include <boost/math/tools/precision.hpp>
22 #include <boost/math/tools/promotion.hpp>
23 #include <boost/math/policies/error_handling.hpp>
24 #include <boost/math/constants/constants.hpp>
25 #include <boost/math/special_functions/math_fwd.hpp>
26 #include <boost/math/special_functions/log1p.hpp>
27 #include <boost/math/special_functions/trunc.hpp>
28 #include <boost/math/special_functions/powm1.hpp>
29 #include <boost/math/special_functions/sqrt1pm1.hpp>
30 #include <boost/math/special_functions/lanczos.hpp>
31 #include <boost/math/special_functions/fpclassify.hpp>
32 #include <boost/math/special_functions/detail/igamma_large.hpp>
33 #include <boost/math/special_functions/detail/unchecked_factorial.hpp>
34 #include <boost/math/special_functions/detail/lgamma_small.hpp>
35 #include <boost/math/special_functions/bernoulli.hpp>
36 #include <boost/math/special_functions/polygamma.hpp>
37 #include <boost/type_traits/is_convertible.hpp>
38 #include <boost/assert.hpp>
39 #include <boost/mpl/greater.hpp>
40 #include <boost/mpl/equal_to.hpp>
41 #include <boost/mpl/greater.hpp>
43 #include <boost/config/no_tr1/cmath.hpp>
47 # pragma warning(push)
48 # pragma warning(disable: 4702) // unreachable code (return after domain_error throw).
49 # pragma warning(disable: 4127) // conditional expression is constant.
50 # pragma warning(disable: 4100) // unreferenced formal parameter.
51 // Several variables made comments,
52 // but some difficulty as whether referenced on not may depend on macro values.
53 // So to be safe, 4100 warnings suppressed.
54 // TODO - revisit this?
57 namespace boost{ namespace math{
62 inline bool is_odd(T v, const boost::true_type&)
64 int i = static_cast<int>(v);
68 inline bool is_odd(T v, const boost::false_type&)
70 // Oh dear can't cast T to int!
72 T modulus = v - 2 * floor(v/2);
73 return static_cast<bool>(modulus != 0);
76 inline bool is_odd(T v)
78 return is_odd(v, ::boost::is_convertible<T, int>());
84 // Ad hoc function calculates x * sin(pi * x),
85 // taking extra care near when x is near a whole number.
104 BOOST_ASSERT(fl >= 0);
107 T result = sin(dist*boost::math::constants::pi<T>());
108 return sign*z*result;
109 } // template <class T> T sinpx(T z)
111 // tgamma(z), with Lanczos support:
113 template <class T, class Policy, class Lanczos>
114 T gamma_imp(T z, const Policy& pol, const Lanczos& l)
120 #ifdef BOOST_MATH_INSTRUMENT
121 static bool b = false;
124 std::cout << "tgamma_imp called with " << typeid(z).name() << " " << typeid(l).name() << std::endl;
128 static const char* function = "boost::math::tgamma<%1%>(%1%)";
133 return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
136 result = gamma_imp(T(-z), pol, l) * sinpx(z);
137 BOOST_MATH_INSTRUMENT_VARIABLE(result);
138 if((fabs(result) < 1) && (tools::max_value<T>() * fabs(result) < boost::math::constants::pi<T>()))
139 return -boost::math::sign(result) * policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
140 result = -boost::math::constants::pi<T>() / result;
142 return policies::raise_underflow_error<T>(function, "Result of tgamma is too small to represent.", pol);
143 if((boost::math::fpclassify)(result) == (int)FP_SUBNORMAL)
144 return policies::raise_denorm_error<T>(function, "Result of tgamma is denormalized.", result, pol);
145 BOOST_MATH_INSTRUMENT_VARIABLE(result);
156 BOOST_MATH_INSTRUMENT_VARIABLE(result);
157 if((floor(z) == z) && (z < max_factorial<T>::value))
159 result *= unchecked_factorial<T>(itrunc(z, pol) - 1);
160 BOOST_MATH_INSTRUMENT_VARIABLE(result);
162 else if (z < tools::root_epsilon<T>())
164 if (z < 1 / tools::max_value<T>())
165 result = policies::raise_overflow_error<T>(function, 0, pol);
166 result *= 1 / z - constants::euler<T>();
170 result *= Lanczos::lanczos_sum(z);
171 T zgh = (z + static_cast<T>(Lanczos::g()) - boost::math::constants::half<T>());
173 BOOST_MATH_INSTRUMENT_VARIABLE(result);
174 BOOST_MATH_INSTRUMENT_VARIABLE(tools::log_max_value<T>());
175 if(z * lzgh > tools::log_max_value<T>())
177 // we're going to overflow unless this is done with care:
178 BOOST_MATH_INSTRUMENT_VARIABLE(zgh);
179 if(lzgh * z / 2 > tools::log_max_value<T>())
180 return boost::math::sign(result) * policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
181 T hp = pow(zgh, (z / 2) - T(0.25));
182 BOOST_MATH_INSTRUMENT_VARIABLE(hp);
183 result *= hp / exp(zgh);
184 BOOST_MATH_INSTRUMENT_VARIABLE(result);
185 if(tools::max_value<T>() / hp < result)
186 return boost::math::sign(result) * policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
188 BOOST_MATH_INSTRUMENT_VARIABLE(result);
192 BOOST_MATH_INSTRUMENT_VARIABLE(zgh);
193 BOOST_MATH_INSTRUMENT_VARIABLE(pow(zgh, z - boost::math::constants::half<T>()));
194 BOOST_MATH_INSTRUMENT_VARIABLE(exp(zgh));
195 result *= pow(zgh, z - boost::math::constants::half<T>()) / exp(zgh);
196 BOOST_MATH_INSTRUMENT_VARIABLE(result);
202 // lgamma(z) with Lanczos support:
204 template <class T, class Policy, class Lanczos>
205 T lgamma_imp(T z, const Policy& pol, const Lanczos& l, int* sign = 0)
207 #ifdef BOOST_MATH_INSTRUMENT
208 static bool b = false;
211 std::cout << "lgamma_imp called with " << typeid(z).name() << " " << typeid(l).name() << std::endl;
218 static const char* function = "boost::math::lgamma<%1%>(%1%)";
222 if(z <= -tools::root_epsilon<T>())
224 // reflection formula:
226 return policies::raise_pole_error<T>(function, "Evaluation of lgamma at a negative integer %1%.", z, pol);
238 result = log(boost::math::constants::pi<T>()) - lgamma_imp(z, pol, l) - log(t);
240 else if (z < tools::root_epsilon<T>())
243 return policies::raise_pole_error<T>(function, "Evaluation of lgamma at %1%.", z, pol);
244 if (fabs(z) < 1 / tools::max_value<T>())
245 result = -log(fabs(z));
247 result = log(fabs(1 / z - constants::euler<T>()));
253 typedef typename policies::precision<T, Policy>::type precision_type;
254 typedef typename mpl::if_<
256 mpl::less_equal<precision_type, mpl::int_<64> >,
257 mpl::greater<precision_type, mpl::int_<0> >
262 mpl::less_equal<precision_type, mpl::int_<113> >,
263 mpl::greater<precision_type, mpl::int_<0> >
265 mpl::int_<113>, mpl::int_<0> >::type
267 result = lgamma_small_imp<T>(z, T(z - 1), T(z - 2), tag_type(), pol, l);
269 else if((z >= 3) && (z < 100) && (std::numeric_limits<T>::max_exponent >= 1024))
271 // taking the log of tgamma reduces the error, no danger of overflow here:
272 result = log(gamma_imp(z, pol, l));
276 // regular evaluation:
277 T zgh = static_cast<T>(z + Lanczos::g() - boost::math::constants::half<T>());
278 result = log(zgh) - 1;
281 // Only add on the lanczos sum part if we're going to need it:
283 if(result * tools::epsilon<T>() < 20)
284 result += log(Lanczos::lanczos_sum_expG_scaled(z));
293 // Incomplete gamma functions follow:
296 struct upper_incomplete_gamma_fract
302 typedef std::pair<T,T> result_type;
304 upper_incomplete_gamma_fract(T a1, T z1)
305 : z(z1-a1+1), a(a1), k(0)
309 result_type operator()()
313 return result_type(k * (a - k), z);
318 inline T upper_gamma_fraction(T a, T z, T eps)
320 // Multiply result by z^a * e^-z to get the full
321 // upper incomplete integral. Divide by tgamma(z)
323 upper_incomplete_gamma_fract<T> f(a, z);
324 return 1 / (z - a + 1 + boost::math::tools::continued_fraction_a(f, eps));
328 struct lower_incomplete_gamma_series
333 typedef T result_type;
334 lower_incomplete_gamma_series(T a1, T z1) : a(a1), z(z1), result(1){}
345 template <class T, class Policy>
346 inline T lower_gamma_series(T a, T z, const Policy& pol, T init_value = 0)
348 // Multiply result by ((z^a) * (e^-z) / a) to get the full
349 // lower incomplete integral. Then divide by tgamma(a)
350 // to get the normalised value.
351 lower_incomplete_gamma_series<T> s(a, z);
352 boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
353 T factor = policies::get_epsilon<T, Policy>();
354 T result = boost::math::tools::sum_series(s, factor, max_iter, init_value);
355 policies::check_series_iterations<T>("boost::math::detail::lower_gamma_series<%1%>(%1%)", max_iter, pol);
360 // Fully generic tgamma and lgamma use Stirling's approximation
361 // with Bernoulli numbers.
364 std::size_t highest_bernoulli_index()
366 const float digits10_of_type = (std::numeric_limits<T>::is_specialized
367 ? static_cast<float>(std::numeric_limits<T>::digits10)
368 : static_cast<float>(boost::math::tools::digits<T>() * 0.301F));
370 // Find the high index n for Bn to produce the desired precision in Stirling's calculation.
371 return static_cast<std::size_t>(18.0F + (0.6F * digits10_of_type));
375 int minimum_argument_for_bernoulli_recursion()
377 const float digits10_of_type = (std::numeric_limits<T>::is_specialized
378 ? static_cast<float>(std::numeric_limits<T>::digits10)
379 : static_cast<float>(boost::math::tools::digits<T>() * 0.301F));
381 const float limit = std::ceil(std::pow(1.0f / std::ldexp(1.0f, 1-boost::math::tools::digits<T>()), 1.0f / 20.0f));
383 return (int)((std::min)(digits10_of_type * 1.7F, limit));
386 template <class T, class Policy>
387 T scaled_tgamma_no_lanczos(const T& z, const Policy& pol, bool islog = false)
391 // Calculates tgamma(z) / (z/e)^z
392 // Requires that our argument is large enough for Sterling's approximation to hold.
393 // Used internally when combining gamma's of similar magnitude without logarithms.
395 BOOST_ASSERT(minimum_argument_for_bernoulli_recursion<T>() <= z);
397 // Perform the Bernoulli series expansion of Stirling's approximation.
399 const std::size_t number_of_bernoullis_b2n = policies::get_max_series_iterations<Policy>();
401 T one_over_x_pow_two_n_minus_one = 1 / z;
402 const T one_over_x2 = one_over_x_pow_two_n_minus_one * one_over_x_pow_two_n_minus_one;
403 T sum = (boost::math::bernoulli_b2n<T>(1) / 2) * one_over_x_pow_two_n_minus_one;
404 const T target_epsilon_to_break_loop = sum * boost::math::tools::epsilon<T>();
405 const T half_ln_two_pi_over_z = sqrt(boost::math::constants::two_pi<T>() / z);
406 T last_term = 2 * sum;
408 for (std::size_t n = 2U;; ++n)
410 one_over_x_pow_two_n_minus_one *= one_over_x2;
412 const std::size_t n2 = static_cast<std::size_t>(n * 2U);
414 const T term = (boost::math::bernoulli_b2n<T>(static_cast<int>(n)) * one_over_x_pow_two_n_minus_one) / (n2 * (n2 - 1U));
416 if ((n >= 3U) && (abs(term) < target_epsilon_to_break_loop))
418 // We have reached the desired precision in Stirling's expansion.
419 // Adding additional terms to the sum of this divergent asymptotic
420 // expansion will not improve the result.
422 // Break from the loop.
425 if (n > number_of_bernoullis_b2n)
426 return policies::raise_evaluation_error("scaled_tgamma_no_lanczos<%1%>()", "Exceeded maximum series iterations without reaching convergence, best approximation was %1%", T(exp(sum) * half_ln_two_pi_over_z), pol);
430 // Sanity check for divergence:
431 T fterm = fabs(term);
432 if(fterm > last_term)
433 return policies::raise_evaluation_error("scaled_tgamma_no_lanczos<%1%>()", "Series became divergent without reaching convergence, best approximation was %1%", T(exp(sum) * half_ln_two_pi_over_z), pol);
437 // Complete Stirling's approximation.
438 T scaled_gamma_value = islog ? T(sum + log(half_ln_two_pi_over_z)) : T(exp(sum) * half_ln_two_pi_over_z);
439 return scaled_gamma_value;
442 // Forward declaration of the lgamma_imp template specialization.
443 template <class T, class Policy>
444 T lgamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos&, int* sign = 0);
446 template <class T, class Policy>
447 T gamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos&)
451 static const char* function = "boost::math::tgamma<%1%>(%1%)";
453 // Check if the argument of tgamma is identically zero.
454 const bool is_at_zero = (z == 0);
456 if((boost::math::isnan)(z) || (is_at_zero) || ((boost::math::isinf)(z) && (z < 0)))
457 return policies::raise_domain_error<T>(function, "Evaluation of tgamma at %1%.", z, pol);
459 const bool b_neg = (z < 0);
461 const bool floor_of_z_is_equal_to_z = (floor(z) == z);
463 // Special case handling of small factorials:
464 if((!b_neg) && floor_of_z_is_equal_to_z && (z < boost::math::max_factorial<T>::value))
466 return boost::math::unchecked_factorial<T>(itrunc(z) - 1);
469 // Make a local, unsigned copy of the input argument.
470 T zz((!b_neg) ? z : -z);
472 // Special case for ultra-small z:
473 if(zz < tools::cbrt_epsilon<T>())
476 const T a1(boost::math::constants::euler<T>());
477 const T six_euler_squared((boost::math::constants::euler<T>() * boost::math::constants::euler<T>()) * 6);
478 const T a2((six_euler_squared - boost::math::constants::pi_sqr<T>()) / 12);
480 const T inverse_tgamma_series = z * ((a2 * z + a1) * z + a0);
482 return 1 / inverse_tgamma_series;
485 // Scale the argument up for the calculation of lgamma,
486 // and use downward recursion later for the final result.
487 const int min_arg_for_recursion = minimum_argument_for_bernoulli_recursion<T>();
491 if(zz < min_arg_for_recursion)
493 n_recur = boost::math::itrunc(min_arg_for_recursion - zz) + 1;
503 if (zz > tools::log_max_value<T>())
504 return policies::raise_overflow_error<T>(function, 0, pol);
505 if (log(zz) * zz / 2 > tools::log_max_value<T>())
506 return policies::raise_overflow_error<T>(function, 0, pol);
508 T gamma_value = scaled_tgamma_no_lanczos(zz, pol);
509 T power_term = pow(zz, zz / 2);
510 T exp_term = exp(-zz);
511 gamma_value *= (power_term * exp_term);
512 if(!n_recur && (tools::max_value<T>() / power_term < gamma_value))
513 return policies::raise_overflow_error<T>(function, 0, pol);
514 gamma_value *= power_term;
516 // Rescale the result using downward recursion if necessary.
519 // The order of divides is important, if we keep subtracting 1 from zz
520 // we DO NOT get back to z (cancellation error). Further if z < epsilon
521 // we would end up dividing by zero. Also in order to prevent spurious
522 // overflow with the first division, we must save dividing by |z| till last,
523 // so the optimal order of divides is z+1, z+2, z+3...z+n_recur-1,z.
525 for(int k = 1; k < n_recur; ++k)
530 gamma_value /= fabs(z);
533 // Return the result, accounting for possible negative arguments.
536 // Provide special error analysis for:
537 // * arguments in the neighborhood of a negative integer
538 // * arguments exactly equal to a negative integer.
540 // Check if the argument of tgamma is exactly equal to a negative integer.
541 if(floor_of_z_is_equal_to_z)
542 return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
544 gamma_value *= sinpx(z);
546 BOOST_MATH_INSTRUMENT_VARIABLE(gamma_value);
548 const bool result_is_too_large_to_represent = ( (abs(gamma_value) < 1)
549 && ((tools::max_value<T>() * abs(gamma_value)) < boost::math::constants::pi<T>()));
551 if(result_is_too_large_to_represent)
552 return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
554 gamma_value = -boost::math::constants::pi<T>() / gamma_value;
555 BOOST_MATH_INSTRUMENT_VARIABLE(gamma_value);
558 return policies::raise_underflow_error<T>(function, "Result of tgamma is too small to represent.", pol);
560 if((boost::math::fpclassify)(gamma_value) == static_cast<int>(FP_SUBNORMAL))
561 return policies::raise_denorm_error<T>(function, "Result of tgamma is denormalized.", gamma_value, pol);
567 template <class T, class Policy>
568 inline T log_gamma_near_1(const T& z, Policy const& pol)
571 // This is for the multiprecision case where there is
572 // no lanczos support, use a taylor series at z = 1,
573 // see https://www.wolframalpha.com/input/?i=taylor+series+lgamma(x)+at+x+%3D+1
575 BOOST_MATH_STD_USING // ADL of std names
577 BOOST_ASSERT(fabs(z) < 1);
579 T result = -constants::euler<T>() * z;
581 T power_term = z * z / 2;
587 term = power_term * boost::math::polygamma(n - 1, T(1));
591 } while (fabs(result) * tools::epsilon<T>() < fabs(term));
596 template <class T, class Policy>
597 T lgamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos&, int* sign)
601 static const char* function = "boost::math::lgamma<%1%>(%1%)";
603 // Check if the argument of lgamma is identically zero.
604 const bool is_at_zero = (z == 0);
607 return policies::raise_domain_error<T>(function, "Evaluation of lgamma at zero %1%.", z, pol);
608 if((boost::math::isnan)(z))
609 return policies::raise_domain_error<T>(function, "Evaluation of lgamma at %1%.", z, pol);
610 if((boost::math::isinf)(z))
611 return policies::raise_overflow_error<T>(function, 0, pol);
613 const bool b_neg = (z < 0);
615 const bool floor_of_z_is_equal_to_z = (floor(z) == z);
617 // Special case handling of small factorials:
618 if((!b_neg) && floor_of_z_is_equal_to_z && (z < boost::math::max_factorial<T>::value))
622 return log(boost::math::unchecked_factorial<T>(itrunc(z) - 1));
625 // Make a local, unsigned copy of the input argument.
626 T zz((!b_neg) ? z : -z);
628 const int min_arg_for_recursion = minimum_argument_for_bernoulli_recursion<T>();
632 if (zz < min_arg_for_recursion)
634 // Here we simply take the logarithm of tgamma(). This is somewhat
635 // inefficient, but simple. The rationale is that the argument here
636 // is relatively small and overflow is not expected to be likely.
639 if(fabs(z - 1) < 0.25)
641 log_gamma_value = log_gamma_near_1(T(zz - 1), pol);
643 else if(fabs(z - 2) < 0.25)
645 log_gamma_value = log_gamma_near_1(T(zz - 2), pol) + log(zz - 1);
647 else if (z > -tools::root_epsilon<T>())
649 // Reflection formula may fail if z is very close to zero, let the series
650 // expansion for tgamma close to zero do the work:
652 *sign = z < 0 ? -1 : 1;
653 return log(abs(gamma_imp(z, pol, lanczos::undefined_lanczos())));
657 // No issue with spurious overflow in reflection formula,
658 // just fall through to regular code:
659 T g = gamma_imp(zz, pol, lanczos::undefined_lanczos());
662 *sign = g < 0 ? -1 : 1;
664 log_gamma_value = log(abs(g));
669 // Perform the Bernoulli series expansion of Stirling's approximation.
670 T sum = scaled_tgamma_no_lanczos(zz, pol, true);
671 log_gamma_value = zz * (log(zz) - 1) + sum;
674 int sign_of_result = 1;
678 // Provide special error analysis if the argument is exactly
679 // equal to a negative integer.
681 // Check if the argument of lgamma is exactly equal to a negative integer.
682 if(floor_of_z_is_equal_to_z)
683 return policies::raise_pole_error<T>(function, "Evaluation of lgamma at a negative integer %1%.", z, pol);
693 sign_of_result = -sign_of_result;
696 log_gamma_value = - log_gamma_value
697 + log(boost::math::constants::pi<T>())
701 if(sign != static_cast<int*>(0U)) { *sign = sign_of_result; }
703 return log_gamma_value;
707 // This helper calculates tgamma(dz+1)-1 without cancellation errors,
708 // used by the upper incomplete gamma with z < 1:
710 template <class T, class Policy, class Lanczos>
711 T tgammap1m1_imp(T dz, Policy const& pol, const Lanczos& l)
715 typedef typename policies::precision<T,Policy>::type precision_type;
717 typedef typename mpl::if_<
719 mpl::less_equal<precision_type, mpl::int_<0> >,
720 mpl::greater<precision_type, mpl::int_<113> >
723 mpl::and_<is_same<Lanczos, lanczos::lanczos24m113>, mpl::greater<precision_type, mpl::int_<0> > >,
728 mpl::less_equal<precision_type, mpl::int_<64> >,
729 mpl::int_<64>, mpl::int_<113> >::type
737 // Best method is simply to subtract 1 from tgamma:
738 result = boost::math::tgamma(1+dz, pol) - 1;
739 BOOST_MATH_INSTRUMENT_CODE(result);
743 // Use expm1 on lgamma:
744 result = boost::math::expm1(-boost::math::log1p(dz, pol)
745 + lgamma_small_imp<T>(dz+2, dz + 1, dz, tag_type(), pol, l));
746 BOOST_MATH_INSTRUMENT_CODE(result);
753 // Use expm1 on lgamma:
754 result = boost::math::expm1(lgamma_small_imp<T>(dz+1, dz, dz-1, tag_type(), pol, l), pol);
755 BOOST_MATH_INSTRUMENT_CODE(result);
759 // Best method is simply to subtract 1 from tgamma:
760 result = boost::math::tgamma(1+dz, pol) - 1;
761 BOOST_MATH_INSTRUMENT_CODE(result);
768 template <class T, class Policy>
769 inline T tgammap1m1_imp(T z, Policy const& pol,
770 const ::boost::math::lanczos::undefined_lanczos&)
772 BOOST_MATH_STD_USING // ADL of std names
776 return boost::math::expm1(log_gamma_near_1(z, pol));
778 return boost::math::expm1(boost::math::lgamma(1 + z, pol));
782 // Series representation for upper fraction when z is small:
785 struct small_gamma2_series
787 typedef T result_type;
789 small_gamma2_series(T a_, T x_) : result(-x_), x(-x_), apn(a_+1), n(1){}
793 T r = result / (apn);
805 // calculate power term prefix (z^a)(e^-z) used in the non-normalised
806 // incomplete gammas:
808 template <class T, class Policy>
809 T full_igamma_prefix(T a, T z, const Policy& pol)
814 if (z > tools::max_value<T>())
820 if((alz < tools::log_max_value<T>()) && (-z > tools::log_min_value<T>()))
822 prefix = pow(z, a) * exp(-z);
826 prefix = pow(z / exp(z/a), a);
830 prefix = exp(alz - z);
835 if(alz > tools::log_min_value<T>())
837 prefix = pow(z, a) * exp(-z);
839 else if(z/a < tools::log_max_value<T>())
841 prefix = pow(z / exp(z/a), a);
845 prefix = exp(alz - z);
849 // This error handling isn't very good: it happens after the fact
850 // rather than before it...
852 if((boost::math::fpclassify)(prefix) == (int)FP_INFINITE)
853 return 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);
858 // Compute (z^a)(e^-z)/tgamma(a)
859 // most if the error occurs in this function:
861 template <class T, class Policy, class Lanczos>
862 T regularised_gamma_prefix(T a, T z, const Policy& pol, const Lanczos& l)
865 if (z >= tools::max_value<T>())
867 T agh = a + static_cast<T>(Lanczos::g()) - T(0.5);
869 T d = ((z - a) - static_cast<T>(Lanczos::g()) + T(0.5)) / agh;
874 // We have to treat a < 1 as a special case because our Lanczos
875 // approximations are optimised against the factorials with a > 1,
876 // and for high precision types especially (128-bit reals for example)
877 // very small values of a can give rather eroneous results for gamma
878 // unless we do this:
880 // TODO: is this still required? Lanczos approx should be better now?
882 if(z <= tools::log_min_value<T>())
884 // Oh dear, have to use logs, should be free of cancellation errors though:
885 return exp(a * log(z) - z - lgamma_imp(a, pol, l));
889 // direct calculation, no danger of overflow as gamma(a) < 1/a
891 return pow(z, a) * exp(-z) / gamma_imp(a, pol, l);
894 else if((fabs(d*d*a) <= 100) && (a > 150))
896 // special case for large a and a ~ z.
897 prefix = a * boost::math::log1pmx(d, pol) + z * static_cast<T>(0.5 - Lanczos::g()) / agh;
898 prefix = exp(prefix);
904 // direct computation is most accurate, but use various fallbacks
905 // for different parts of the problem domain:
907 T alz = a * log(z / agh);
909 if(((std::min)(alz, amz) <= tools::log_min_value<T>()) || ((std::max)(alz, amz) >= tools::log_max_value<T>()))
912 if(((std::min)(alz, amz)/2 > tools::log_min_value<T>()) && ((std::max)(alz, amz)/2 < tools::log_max_value<T>()))
914 // compute square root of the result and then square it:
915 T sq = pow(z / agh, a / 2) * exp(amz / 2);
918 else if(((std::min)(alz, amz)/4 > tools::log_min_value<T>()) && ((std::max)(alz, amz)/4 < tools::log_max_value<T>()) && (z > a))
920 // compute the 4th root of the result then square it twice:
921 T sq = pow(z / agh, a / 4) * exp(amz / 4);
925 else if((amza > tools::log_min_value<T>()) && (amza < tools::log_max_value<T>()))
927 prefix = pow((z * exp(amza)) / agh, a);
931 prefix = exp(alz + amz);
936 prefix = pow(z / agh, a) * exp(amz);
939 prefix *= sqrt(agh / boost::math::constants::e<T>()) / Lanczos::lanczos_sum_expG_scaled(a);
943 // And again, without Lanczos support:
945 template <class T, class Policy>
946 T regularised_gamma_prefix(T a, T z, const Policy& pol, const lanczos::undefined_lanczos& l)
950 if((a < 1) && (z < 1))
952 // No overflow possible since the power terms tend to unity as a,z -> 0
953 return pow(z, a) * exp(-z) / boost::math::tgamma(a, pol);
955 else if(a > minimum_argument_for_bernoulli_recursion<T>())
957 T scaled_gamma = scaled_tgamma_no_lanczos(a, pol);
958 T power_term = pow(z / a, a / 2);
960 if ((0 == power_term) || (fabs(a_minus_z) > tools::log_max_value<T>()))
962 // The result is probably zero, but we need to be sure:
963 return exp(a * log(z / a) + a_minus_z - log(scaled_gamma));
965 return (power_term * exp(a_minus_z)) * (power_term / scaled_gamma);
970 // Usual case is to calculate the prefix at a+shift and recurse down
971 // to the value we want:
973 const int min_z = minimum_argument_for_bernoulli_recursion<T>();
974 long shift = 1 + ltrunc(min_z - a);
975 T result = regularised_gamma_prefix(T(a + shift), z, pol, l);
978 for (long i = 0; i < shift; ++i)
988 // We failed, most probably we have z << 1, try again, this time
989 // we calculate z^a e^-z / tgamma(a+shift), combining power terms
990 // as we go. And again recurse down to the result.
992 T scaled_gamma = scaled_tgamma_no_lanczos(T(a + shift), pol);
993 T power_term_1 = pow(z / (a + shift), a);
994 T power_term_2 = pow(a + shift, -shift);
995 T power_term_3 = exp(a + shift - z);
996 if ((0 == power_term_1) || (0 == power_term_2) || (0 == power_term_3) || (fabs(a + shift - z) > tools::log_max_value<T>()))
998 // We have no test case that gets here, most likely the type T
999 // has a high precision but low exponent range:
1000 return exp(a * log(z) - z - boost::math::lgamma(a, pol));
1002 result = power_term_1 * power_term_2 * power_term_3 / scaled_gamma;
1003 for (long i = 0; i < shift; ++i)
1012 // Upper gamma fraction for very small a:
1014 template <class T, class Policy>
1015 inline T tgamma_small_upper_part(T a, T x, const Policy& pol, T* pgam = 0, bool invert = false, T* pderivative = 0)
1017 BOOST_MATH_STD_USING // ADL of std functions.
1019 // Compute the full upper fraction (Q) when a is very small:
1022 result = boost::math::tgamma1pm1(a, pol);
1024 *pgam = (result + 1) / a;
1025 T p = boost::math::powm1(x, a, pol);
1028 detail::small_gamma2_series<T> s(a, x);
1029 boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>() - 10;
1032 *pderivative = p / (*pgam * exp(x));
1033 T init_value = invert ? *pgam : 0;
1034 result = -p * tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, (init_value - result) / p);
1035 policies::check_series_iterations<T>("boost::math::tgamma_small_upper_part<%1%>(%1%, %1%)", max_iter, pol);
1041 // Upper gamma fraction for integer a:
1043 template <class T, class Policy>
1044 inline T finite_gamma_q(T a, T x, Policy const& pol, T* pderivative = 0)
1047 // Calculates normalised Q when a is an integer:
1049 BOOST_MATH_STD_USING
1055 for(unsigned n = 1; n < a; ++n)
1064 *pderivative = e * pow(x, a) / boost::math::unchecked_factorial<T>(itrunc(T(a - 1), pol));
1069 // Upper gamma fraction for half integer a:
1071 template <class T, class Policy>
1072 T finite_half_gamma_q(T a, T x, T* p_derivative, const Policy& pol)
1075 // Calculates normalised Q when a is a half-integer:
1077 BOOST_MATH_STD_USING
1078 T e = boost::math::erfc(sqrt(x), pol);
1079 if((e != 0) && (a > 1))
1081 T term = exp(-x) / sqrt(constants::pi<T>() * x);
1083 static const T half = T(1) / 2;
1086 for(unsigned n = 2; n < a; ++n)
1098 else if(p_derivative)
1100 // We'll be dividing by x later, so calculate derivative * x:
1101 *p_derivative = sqrt(x) * exp(-x) / constants::root_pi<T>();
1106 // Asymptotic approximation for large argument, see: https://dlmf.nist.gov/8.11#E2
1109 struct incomplete_tgamma_large_x_series
1111 typedef T result_type;
1112 incomplete_tgamma_large_x_series(const T& a, const T& x)
1113 : a_poch(a - 1), z(x), term(1) {}
1124 template <class T, class Policy>
1125 T incomplete_tgamma_large_x(const T& a, const T& x, const Policy& pol)
1127 BOOST_MATH_STD_USING
1128 incomplete_tgamma_large_x_series<T> s(a, x);
1129 boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();
1130 T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);
1131 boost::math::policies::check_series_iterations<T>("boost::math::tgamma<%1%>(%1%,%1%)", max_iter, pol);
1137 // Main incomplete gamma entry point, handles all four incomplete gamma's:
1139 template <class T, class Policy>
1140 T gamma_incomplete_imp(T a, T x, bool normalised, bool invert,
1141 const Policy& pol, T* p_derivative)
1143 static const char* function = "boost::math::gamma_p<%1%>(%1%, %1%)";
1145 return policies::raise_domain_error<T>(function, "Argument a to the incomplete gamma function must be greater than zero (got a=%1%).", a, pol);
1147 return policies::raise_domain_error<T>(function, "Argument x to the incomplete gamma function must be >= 0 (got x=%1%).", x, pol);
1149 BOOST_MATH_STD_USING
1151 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
1153 T result = 0; // Just to avoid warning C4701: potentially uninitialized local variable 'result' used
1155 if(a >= max_factorial<T>::value && !normalised)
1158 // When we're computing the non-normalized incomplete gamma
1159 // and a is large the result is rather hard to compute unless
1160 // we use logs. There are really two options - if x is a long
1161 // way from a in value then we can reliably use methods 2 and 4
1162 // below in logarithmic form and go straight to the result.
1163 // Otherwise we let the regularized gamma take the strain
1164 // (the result is unlikely to unerflow in the central region anyway)
1165 // and combine with lgamma in the hopes that we get a finite result.
1167 if(invert && (a * 4 < x))
1169 // This is method 4 below, done in logs:
1170 result = a * log(x) - x;
1172 *p_derivative = exp(result);
1173 result += log(upper_gamma_fraction(a, x, policies::get_epsilon<T, Policy>()));
1175 else if(!invert && (a > 4 * x))
1177 // This is method 2 below, done in logs:
1178 result = a * log(x) - x;
1180 *p_derivative = exp(result);
1182 result += log(detail::lower_gamma_series(a, x, pol, init_value) / a);
1186 result = gamma_incomplete_imp(a, x, true, invert, pol, p_derivative);
1191 // Try http://functions.wolfram.com/06.06.06.0039.01
1192 result = 1 + 1 / (12 * a) + 1 / (288 * a * a);
1193 result = log(result) - a + (a - 0.5f) * log(a) + log(boost::math::constants::root_two_pi<T>());
1195 *p_derivative = exp(a * log(x) - x);
1199 // This is method 2 below, done in logs, we're really outside the
1200 // range of this method, but since the result is almost certainly
1201 // infinite, we should probably be OK:
1202 result = a * log(x) - x;
1204 *p_derivative = exp(result);
1206 result += log(detail::lower_gamma_series(a, x, pol, init_value) / a);
1211 result = log(result) + boost::math::lgamma(a, pol);
1214 if(result > tools::log_max_value<T>())
1215 return policies::raise_overflow_error<T>(function, 0, pol);
1219 BOOST_ASSERT((p_derivative == 0) || (normalised == true));
1221 bool is_int, is_half_int;
1222 bool is_small_a = (a < 30) && (a <= x + 1) && (x < tools::log_max_value<T>());
1227 is_half_int = is_int ? false : (fabs(fa - a) == 0.5f);
1231 is_int = is_half_int = false;
1236 if(is_int && (x > 0.6))
1238 // calculate Q via finite sum:
1242 else if(is_half_int && (x > 0.2))
1244 // calculate Q via finite sum for half integer a:
1248 else if((x < tools::root_epsilon<T>()) && (a > 1))
1252 else if ((x > 1000) && ((a < x) || (fabs(a - 50) / x < 1)))
1254 // calculate Q via asymptotic approximation:
1261 // Changeover criterion chosen to give a changeover at Q ~ 0.33
1263 if(-0.4 / log(x) < a)
1275 // Changover here occurs when P ~ 0.75 or Q ~ 0.25:
1289 // Begin by testing whether we're in the "bad" zone
1290 // where the result will be near 0.5 and the usual
1291 // series and continued fractions are slow to converge:
1293 bool use_temme = false;
1294 if(normalised && std::numeric_limits<T>::is_specialized && (a > 20))
1296 T sigma = fabs((x-a)/a);
1297 if((a > 200) && (policies::digits<T, Policy>() <= 113))
1300 // This limit is chosen so that we use Temme's expansion
1301 // only if the result would be larger than about 10^-6.
1302 // Below that the regular series and continued fractions
1303 // converge OK, and if we use Temme's method we get increasing
1304 // errors from the dominant erfc term as it's (inexact) argument
1305 // increases in magnitude.
1307 if(20 / a > sigma * sigma)
1310 else if(policies::digits<T, Policy>() <= 64)
1312 // Note in this zone we can't use Temme's expansion for
1313 // types longer than an 80-bit real:
1314 // it would require too many terms in the polynomials.
1326 // Regular case where the result will not be too close to 0.5.
1328 // Changeover here occurs at P ~ Q ~ 0.5
1329 // Note that series computation of P is about x2 faster than continued fraction
1330 // calculation of Q, so try and use the CF only when really necessary, especially
1333 if(x - (1 / (3 * x)) < a)
1349 result = finite_gamma_q(a, x, pol, p_derivative);
1350 if(normalised == false)
1351 result *= boost::math::tgamma(a, pol);
1356 result = finite_half_gamma_q(a, x, p_derivative, pol);
1357 if(normalised == false)
1358 result *= boost::math::tgamma(a, pol);
1359 if(p_derivative && (*p_derivative == 0))
1360 *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
1366 result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
1368 *p_derivative = result;
1372 // If we're going to be inverting the result then we can
1373 // reduce the number of series evaluations by quite
1374 // a few iterations if we set an initial value for the
1375 // series sum based on what we'll end up subtracting it from
1377 // Have to be careful though that this optimization doesn't
1378 // lead to spurious numberic overflow. Note that the
1379 // scary/expensive overflow checks below are more often
1380 // than not bypassed in practice for "sensible" input
1384 bool optimised_invert = false;
1387 init_value = (normalised ? 1 : boost::math::tgamma(a, pol));
1388 if(normalised || (result >= 1) || (tools::max_value<T>() * result > init_value))
1390 init_value /= result;
1391 if(normalised || (a < 1) || (tools::max_value<T>() / a > init_value))
1394 optimised_invert = true;
1402 result *= detail::lower_gamma_series(a, x, pol, init_value) / a;
1403 if(optimised_invert)
1416 result = tgamma_small_upper_part(a, x, pol, &g, invert, p_derivative);
1425 result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
1427 *p_derivative = result;
1429 result *= upper_gamma_fraction(a, x, policies::get_epsilon<T, Policy>());
1435 // Use compile time dispatch to the appropriate
1436 // Temme asymptotic expansion. This may be dead code
1437 // if T does not have numeric limits support, or has
1438 // too many digits for the most precise version of
1439 // these expansions, in that case we'll be calling
1440 // an empty function.
1442 typedef typename policies::precision<T, Policy>::type precision_type;
1444 typedef typename mpl::if_<
1445 mpl::or_<mpl::equal_to<precision_type, mpl::int_<0> >,
1446 mpl::greater<precision_type, mpl::int_<113> > >,
1449 mpl::less_equal<precision_type, mpl::int_<53> >,
1452 mpl::less_equal<precision_type, mpl::int_<64> >,
1459 result = igamma_temme_large(a, x, pol, static_cast<tag_type const*>(0));
1463 *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
1468 // x is so small that P is necessarily very small too,
1469 // use http://functions.wolfram.com/GammaBetaErf/GammaRegularized/06/01/05/01/01/
1470 result = !normalised ? pow(x, a) / (a) : pow(x, a) / boost::math::tgamma(a + 1, pol);
1471 result *= 1 - a * x / (a + 1);
1473 *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
1480 result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
1482 *p_derivative = result;
1485 result *= incomplete_tgamma_large_x(a, x, pol);
1490 if(normalised && (result > 1))
1494 T gam = normalised ? 1 : boost::math::tgamma(a, pol);
1495 result = gam - result;
1500 // Need to convert prefix term to derivative:
1502 if((x < 1) && (tools::max_value<T>() * x < *p_derivative))
1504 // overflow, just return an arbitrarily large value:
1505 *p_derivative = tools::max_value<T>() / 2;
1515 // Ratios of two gamma functions:
1517 template <class T, class Policy, class Lanczos>
1518 T tgamma_delta_ratio_imp_lanczos(T z, T delta, const Policy& pol, const Lanczos& l)
1520 BOOST_MATH_STD_USING
1521 if(z < tools::epsilon<T>())
1524 // We get spurious numeric overflow unless we're very careful, this
1525 // can occur either inside Lanczos::lanczos_sum(z) or in the
1526 // final combination of terms, to avoid this, split the product up
1527 // into 2 (or 3) parts:
1529 // G(z) / G(L) = 1 / (z * G(L)) ; z < eps, L = z + delta = delta
1530 // z * G(L) = z * G(lim) * (G(L)/G(lim)) ; lim = largest factorial
1532 if(boost::math::max_factorial<T>::value < delta)
1534 T ratio = tgamma_delta_ratio_imp_lanczos(delta, T(boost::math::max_factorial<T>::value - delta), pol, l);
1536 ratio *= boost::math::unchecked_factorial<T>(boost::math::max_factorial<T>::value - 1);
1541 return 1 / (z * boost::math::tgamma(z + delta, pol));
1544 T zgh = static_cast<T>(z + Lanczos::g() - constants::half<T>());
1548 if(fabs(delta) < 10)
1549 result = exp((constants::half<T>() - z) * boost::math::log1p(delta / zgh, pol));
1555 if(fabs(delta) < 10)
1557 result = exp((constants::half<T>() - z) * boost::math::log1p(delta / zgh, pol));
1561 result = pow(zgh / (zgh + delta), z - constants::half<T>());
1563 // Split the calculation up to avoid spurious overflow:
1564 result *= Lanczos::lanczos_sum(z) / Lanczos::lanczos_sum(T(z + delta));
1566 result *= pow(constants::e<T>() / (zgh + delta), delta);
1570 // And again without Lanczos support this time:
1572 template <class T, class Policy>
1573 T tgamma_delta_ratio_imp_lanczos(T z, T delta, const Policy& pol, const lanczos::undefined_lanczos& l)
1575 BOOST_MATH_STD_USING
1578 // We adjust z and delta so that both z and z+delta are large enough for
1579 // Sterling's approximation to hold. We can then calculate the ratio
1580 // for the adjusted values, and rescale back down to z and z+delta.
1582 // Get the required shifts first:
1584 long numerator_shift = 0;
1585 long denominator_shift = 0;
1586 const int min_z = minimum_argument_for_bernoulli_recursion<T>();
1589 numerator_shift = 1 + ltrunc(min_z - z);
1590 if (min_z > z + delta)
1591 denominator_shift = 1 + ltrunc(min_z - z - delta);
1593 // If the shifts are zero, then we can just combine scaled tgamma's
1594 // and combine the remaining terms:
1596 if (numerator_shift == 0 && denominator_shift == 0)
1598 T scaled_tgamma_num = scaled_tgamma_no_lanczos(z, pol);
1599 T scaled_tgamma_denom = scaled_tgamma_no_lanczos(T(z + delta), pol);
1600 T result = scaled_tgamma_num / scaled_tgamma_denom;
1601 result *= exp(z * boost::math::log1p(-delta / (z + delta), pol)) * pow((delta + z) / constants::e<T>(), -delta);
1605 // We're going to have to rescale first, get the adjusted z and delta values,
1606 // plus the ratio for the adjusted values:
1608 T zz = z + numerator_shift;
1609 T dd = delta - (numerator_shift - denominator_shift);
1610 T ratio = tgamma_delta_ratio_imp_lanczos(zz, dd, pol, l);
1612 // Use gamma recurrence relations to get back to the original
1615 for (long long i = 0; i < numerator_shift; ++i)
1618 if (i < denominator_shift)
1619 ratio *= (z + delta + i);
1621 for (long long i = numerator_shift; i < denominator_shift; ++i)
1623 ratio *= (z + delta + i);
1628 template <class T, class Policy>
1629 T tgamma_delta_ratio_imp(T z, T delta, const Policy& pol)
1631 BOOST_MATH_STD_USING
1633 if((z <= 0) || (z + delta <= 0))
1635 // This isn't very sofisticated, or accurate, but it does work:
1636 return boost::math::tgamma(z, pol) / boost::math::tgamma(z + delta, pol);
1639 if(floor(delta) == delta)
1644 // Both z and delta are integers, see if we can just use table lookup
1645 // of the factorials to get the result:
1647 if((z <= max_factorial<T>::value) && (z + delta <= max_factorial<T>::value))
1649 return unchecked_factorial<T>((unsigned)itrunc(z, pol) - 1) / unchecked_factorial<T>((unsigned)itrunc(T(z + delta), pol) - 1);
1652 if(fabs(delta) < 20)
1655 // delta is a small integer, we can use a finite product:
1663 while(0 != (delta += 1))
1673 while(0 != (delta -= 1))
1682 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
1683 return tgamma_delta_ratio_imp_lanczos(z, delta, pol, lanczos_type());
1686 template <class T, class Policy>
1687 T tgamma_ratio_imp(T x, T y, const Policy& pol)
1689 BOOST_MATH_STD_USING
1691 if((x <= 0) || (boost::math::isinf)(x))
1692 return policies::raise_domain_error<T>("boost::math::tgamma_ratio<%1%>(%1%, %1%)", "Gamma function ratios only implemented for positive arguments (got a=%1%).", x, pol);
1693 if((y <= 0) || (boost::math::isinf)(y))
1694 return policies::raise_domain_error<T>("boost::math::tgamma_ratio<%1%>(%1%, %1%)", "Gamma function ratios only implemented for positive arguments (got b=%1%).", y, pol);
1696 if(x <= tools::min_value<T>())
1698 // Special case for denorms...Ugh.
1699 T shift = ldexp(T(1), tools::digits<T>());
1700 return shift * tgamma_ratio_imp(T(x * shift), y, pol);
1703 if((x < max_factorial<T>::value) && (y < max_factorial<T>::value))
1705 // Rather than subtracting values, lets just call the gamma functions directly:
1706 return boost::math::tgamma(x, pol) / boost::math::tgamma(y, pol);
1711 if(y < 2 * max_factorial<T>::value)
1713 // We need to sidestep on x as well, otherwise we'll underflow
1714 // before we get to factor in the prefix term:
1717 while(y >= max_factorial<T>::value)
1722 return prefix * boost::math::tgamma(x, pol) / boost::math::tgamma(y, pol);
1725 // result is almost certainly going to underflow to zero, try logs just in case:
1727 return exp(boost::math::lgamma(x, pol) - boost::math::lgamma(y, pol));
1731 if(x < 2 * max_factorial<T>::value)
1733 // We need to sidestep on y as well, otherwise we'll overflow
1734 // before we get to factor in the prefix term:
1737 while(x >= max_factorial<T>::value)
1742 return prefix * boost::math::tgamma(x, pol) / boost::math::tgamma(y, pol);
1745 // Result will almost certainly overflow, try logs just in case:
1747 return exp(boost::math::lgamma(x, pol) - boost::math::lgamma(y, pol));
1750 // Regular case, x and y both large and similar in magnitude:
1752 return boost::math::tgamma_delta_ratio(x, y - x, pol);
1755 template <class T, class Policy>
1756 T gamma_p_derivative_imp(T a, T x, const Policy& pol)
1758 BOOST_MATH_STD_USING
1760 // Usual error checks first:
1763 return 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);
1765 return 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);
1767 // Now special cases:
1771 return (a > 1) ? 0 :
1772 (a == 1) ? 1 : policies::raise_overflow_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", 0, pol);
1777 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
1778 T f1 = detail::regularised_gamma_prefix(a, x, pol, lanczos_type());
1779 if((x < 1) && (tools::max_value<T>() * x < f1))
1782 return policies::raise_overflow_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", 0, pol);
1786 // Underflow in calculation, use logs instead:
1787 f1 = a * log(x) - x - lgamma(a, pol) - log(x);
1796 template <class T, class Policy>
1797 inline typename tools::promote_args<T>::type
1798 tgamma(T z, const Policy& /* pol */, const mpl::true_)
1800 BOOST_FPU_EXCEPTION_GUARD
1801 typedef typename tools::promote_args<T>::type result_type;
1802 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1803 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1804 typedef typename policies::normalise<
1806 policies::promote_float<false>,
1807 policies::promote_double<false>,
1808 policies::discrete_quantile<>,
1809 policies::assert_undefined<> >::type forwarding_policy;
1810 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%)");
1813 template <class T, class Policy>
1814 struct igamma_initializer
1820 typedef typename policies::precision<T, Policy>::type precision_type;
1822 typedef typename mpl::if_<
1823 mpl::or_<mpl::equal_to<precision_type, mpl::int_<0> >,
1824 mpl::greater<precision_type, mpl::int_<113> > >,
1827 mpl::less_equal<precision_type, mpl::int_<53> >,
1830 mpl::less_equal<precision_type, mpl::int_<64> >,
1837 do_init(tag_type());
1840 static void do_init(const mpl::int_<N>&)
1842 // If std::numeric_limits<T>::digits is zero, we must not call
1843 // our inituialization code here as the precision presumably
1844 // varies at runtime, and will not have been set yet. Plus the
1845 // code requiring initialization isn't called when digits == 0.
1846 if(std::numeric_limits<T>::digits)
1848 boost::math::gamma_p(static_cast<T>(400), static_cast<T>(400), Policy());
1851 static void do_init(const mpl::int_<53>&){}
1852 void force_instantiate()const{}
1854 static const init initializer;
1855 static void force_instantiate()
1857 initializer.force_instantiate();
1861 template <class T, class Policy>
1862 const typename igamma_initializer<T, Policy>::init igamma_initializer<T, Policy>::initializer;
1864 template <class T, class Policy>
1865 struct lgamma_initializer
1871 typedef typename policies::precision<T, Policy>::type precision_type;
1872 typedef typename mpl::if_<
1874 mpl::less_equal<precision_type, mpl::int_<64> >,
1875 mpl::greater<precision_type, mpl::int_<0> >
1880 mpl::less_equal<precision_type, mpl::int_<113> >,
1881 mpl::greater<precision_type, mpl::int_<0> >
1883 mpl::int_<113>, mpl::int_<0> >::type
1885 do_init(tag_type());
1887 static void do_init(const mpl::int_<64>&)
1889 boost::math::lgamma(static_cast<T>(2.5), Policy());
1890 boost::math::lgamma(static_cast<T>(1.25), Policy());
1891 boost::math::lgamma(static_cast<T>(1.75), Policy());
1893 static void do_init(const mpl::int_<113>&)
1895 boost::math::lgamma(static_cast<T>(2.5), Policy());
1896 boost::math::lgamma(static_cast<T>(1.25), Policy());
1897 boost::math::lgamma(static_cast<T>(1.5), Policy());
1898 boost::math::lgamma(static_cast<T>(1.75), Policy());
1900 static void do_init(const mpl::int_<0>&)
1903 void force_instantiate()const{}
1905 static const init initializer;
1906 static void force_instantiate()
1908 initializer.force_instantiate();
1912 template <class T, class Policy>
1913 const typename lgamma_initializer<T, Policy>::init lgamma_initializer<T, Policy>::initializer;
1915 template <class T1, class T2, class Policy>
1916 inline typename tools::promote_args<T1, T2>::type
1917 tgamma(T1 a, T2 z, const Policy&, const mpl::false_)
1919 BOOST_FPU_EXCEPTION_GUARD
1920 typedef typename tools::promote_args<T1, T2>::type result_type;
1921 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1922 // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1923 typedef typename policies::normalise<
1925 policies::promote_float<false>,
1926 policies::promote_double<false>,
1927 policies::discrete_quantile<>,
1928 policies::assert_undefined<> >::type forwarding_policy;
1930 igamma_initializer<value_type, forwarding_policy>::force_instantiate();
1932 return policies::checked_narrowing_cast<result_type, forwarding_policy>(
1933 detail::gamma_incomplete_imp(static_cast<value_type>(a),
1934 static_cast<value_type>(z), false, true,
1935 forwarding_policy(), static_cast<value_type*>(0)), "boost::math::tgamma<%1%>(%1%, %1%)");
1938 template <class T1, class T2>
1939 inline typename tools::promote_args<T1, T2>::type
1940 tgamma(T1 a, T2 z, const mpl::false_ tag)
1942 return tgamma(a, z, policies::policy<>(), tag);
1946 } // namespace detail
1949 inline typename tools::promote_args<T>::type
1952 return tgamma(z, policies::policy<>());
1955 template <class T, class Policy>
1956 inline typename tools::promote_args<T>::type
1957 lgamma(T z, int* sign, const Policy&)
1959 BOOST_FPU_EXCEPTION_GUARD
1960 typedef typename tools::promote_args<T>::type result_type;
1961 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1962 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1963 typedef typename policies::normalise<
1965 policies::promote_float<false>,
1966 policies::promote_double<false>,
1967 policies::discrete_quantile<>,
1968 policies::assert_undefined<> >::type forwarding_policy;
1970 detail::lgamma_initializer<value_type, forwarding_policy>::force_instantiate();
1972 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%)");
1976 inline typename tools::promote_args<T>::type
1977 lgamma(T z, int* sign)
1979 return lgamma(z, sign, policies::policy<>());
1982 template <class T, class Policy>
1983 inline typename tools::promote_args<T>::type
1984 lgamma(T x, const Policy& pol)
1986 return ::boost::math::lgamma(x, 0, pol);
1990 inline typename tools::promote_args<T>::type
1993 return ::boost::math::lgamma(x, 0, policies::policy<>());
1996 template <class T, class Policy>
1997 inline typename tools::promote_args<T>::type
1998 tgamma1pm1(T z, const Policy& /* pol */)
2000 BOOST_FPU_EXCEPTION_GUARD
2001 typedef typename tools::promote_args<T>::type result_type;
2002 typedef typename policies::evaluation<result_type, Policy>::type value_type;
2003 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
2004 typedef typename policies::normalise<
2006 policies::promote_float<false>,
2007 policies::promote_double<false>,
2008 policies::discrete_quantile<>,
2009 policies::assert_undefined<> >::type forwarding_policy;
2011 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%)");
2015 inline typename tools::promote_args<T>::type
2018 return tgamma1pm1(z, policies::policy<>());
2022 // Full upper incomplete gamma:
2024 template <class T1, class T2>
2025 inline typename tools::promote_args<T1, T2>::type
2029 // Type T2 could be a policy object, or a value, select the
2030 // right overload based on T2:
2032 typedef typename policies::is_policy<T2>::type maybe_policy;
2033 return detail::tgamma(a, z, maybe_policy());
2035 template <class T1, class T2, class Policy>
2036 inline typename tools::promote_args<T1, T2>::type
2037 tgamma(T1 a, T2 z, const Policy& pol)
2039 return detail::tgamma(a, z, pol, mpl::false_());
2042 // Full lower incomplete gamma:
2044 template <class T1, class T2, class Policy>
2045 inline typename tools::promote_args<T1, T2>::type
2046 tgamma_lower(T1 a, T2 z, const Policy&)
2048 BOOST_FPU_EXCEPTION_GUARD
2049 typedef typename tools::promote_args<T1, T2>::type result_type;
2050 typedef typename policies::evaluation<result_type, Policy>::type value_type;
2051 // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
2052 typedef typename policies::normalise<
2054 policies::promote_float<false>,
2055 policies::promote_double<false>,
2056 policies::discrete_quantile<>,
2057 policies::assert_undefined<> >::type forwarding_policy;
2059 detail::igamma_initializer<value_type, forwarding_policy>::force_instantiate();
2061 return policies::checked_narrowing_cast<result_type, forwarding_policy>(
2062 detail::gamma_incomplete_imp(static_cast<value_type>(a),
2063 static_cast<value_type>(z), false, false,
2064 forwarding_policy(), static_cast<value_type*>(0)), "tgamma_lower<%1%>(%1%, %1%)");
2066 template <class T1, class T2>
2067 inline typename tools::promote_args<T1, T2>::type
2068 tgamma_lower(T1 a, T2 z)
2070 return tgamma_lower(a, z, policies::policy<>());
2073 // Regularised upper incomplete gamma:
2075 template <class T1, class T2, class Policy>
2076 inline typename tools::promote_args<T1, T2>::type
2077 gamma_q(T1 a, T2 z, const Policy& /* pol */)
2079 BOOST_FPU_EXCEPTION_GUARD
2080 typedef typename tools::promote_args<T1, T2>::type result_type;
2081 typedef typename policies::evaluation<result_type, Policy>::type value_type;
2082 // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
2083 typedef typename policies::normalise<
2085 policies::promote_float<false>,
2086 policies::promote_double<false>,
2087 policies::discrete_quantile<>,
2088 policies::assert_undefined<> >::type forwarding_policy;
2090 detail::igamma_initializer<value_type, forwarding_policy>::force_instantiate();
2092 return policies::checked_narrowing_cast<result_type, forwarding_policy>(
2093 detail::gamma_incomplete_imp(static_cast<value_type>(a),
2094 static_cast<value_type>(z), true, true,
2095 forwarding_policy(), static_cast<value_type*>(0)), "gamma_q<%1%>(%1%, %1%)");
2097 template <class T1, class T2>
2098 inline typename tools::promote_args<T1, T2>::type
2101 return gamma_q(a, z, policies::policy<>());
2104 // Regularised lower incomplete gamma:
2106 template <class T1, class T2, class Policy>
2107 inline typename tools::promote_args<T1, T2>::type
2108 gamma_p(T1 a, T2 z, const Policy&)
2110 BOOST_FPU_EXCEPTION_GUARD
2111 typedef typename tools::promote_args<T1, T2>::type result_type;
2112 typedef typename policies::evaluation<result_type, Policy>::type value_type;
2113 // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
2114 typedef typename policies::normalise<
2116 policies::promote_float<false>,
2117 policies::promote_double<false>,
2118 policies::discrete_quantile<>,
2119 policies::assert_undefined<> >::type forwarding_policy;
2121 detail::igamma_initializer<value_type, forwarding_policy>::force_instantiate();
2123 return policies::checked_narrowing_cast<result_type, forwarding_policy>(
2124 detail::gamma_incomplete_imp(static_cast<value_type>(a),
2125 static_cast<value_type>(z), true, false,
2126 forwarding_policy(), static_cast<value_type*>(0)), "gamma_p<%1%>(%1%, %1%)");
2128 template <class T1, class T2>
2129 inline typename tools::promote_args<T1, T2>::type
2132 return gamma_p(a, z, policies::policy<>());
2135 // ratios of gamma functions:
2136 template <class T1, class T2, class Policy>
2137 inline typename tools::promote_args<T1, T2>::type
2138 tgamma_delta_ratio(T1 z, T2 delta, const Policy& /* pol */)
2140 BOOST_FPU_EXCEPTION_GUARD
2141 typedef typename tools::promote_args<T1, T2>::type result_type;
2142 typedef typename policies::evaluation<result_type, Policy>::type value_type;
2143 typedef typename policies::normalise<
2145 policies::promote_float<false>,
2146 policies::promote_double<false>,
2147 policies::discrete_quantile<>,
2148 policies::assert_undefined<> >::type forwarding_policy;
2150 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%)");
2152 template <class T1, class T2>
2153 inline typename tools::promote_args<T1, T2>::type
2154 tgamma_delta_ratio(T1 z, T2 delta)
2156 return tgamma_delta_ratio(z, delta, policies::policy<>());
2158 template <class T1, class T2, class Policy>
2159 inline typename tools::promote_args<T1, T2>::type
2160 tgamma_ratio(T1 a, T2 b, const Policy&)
2162 typedef typename tools::promote_args<T1, T2>::type result_type;
2163 typedef typename policies::evaluation<result_type, Policy>::type value_type;
2164 typedef typename policies::normalise<
2166 policies::promote_float<false>,
2167 policies::promote_double<false>,
2168 policies::discrete_quantile<>,
2169 policies::assert_undefined<> >::type forwarding_policy;
2171 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::tgamma_ratio_imp(static_cast<value_type>(a), static_cast<value_type>(b), forwarding_policy()), "boost::math::tgamma_delta_ratio<%1%>(%1%, %1%)");
2173 template <class T1, class T2>
2174 inline typename tools::promote_args<T1, T2>::type
2175 tgamma_ratio(T1 a, T2 b)
2177 return tgamma_ratio(a, b, policies::policy<>());
2180 template <class T1, class T2, class Policy>
2181 inline typename tools::promote_args<T1, T2>::type
2182 gamma_p_derivative(T1 a, T2 x, const Policy&)
2184 BOOST_FPU_EXCEPTION_GUARD
2185 typedef typename tools::promote_args<T1, T2>::type result_type;
2186 typedef typename policies::evaluation<result_type, Policy>::type value_type;
2187 typedef typename policies::normalise<
2189 policies::promote_float<false>,
2190 policies::promote_double<false>,
2191 policies::discrete_quantile<>,
2192 policies::assert_undefined<> >::type forwarding_policy;
2194 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%)");
2196 template <class T1, class T2>
2197 inline typename tools::promote_args<T1, T2>::type
2198 gamma_p_derivative(T1 a, T2 x)
2200 return gamma_p_derivative(a, x, policies::policy<>());
2204 } // namespace boost
2207 # pragma warning(pop)
2210 #include <boost/math/special_functions/detail/igamma_inverse.hpp>
2211 #include <boost/math/special_functions/detail/gamma_inva.hpp>
2212 #include <boost/math/special_functions/erf.hpp>
2214 #endif // BOOST_MATH_SF_GAMMA_HPP