gamma.hpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218
  1. // Copyright John Maddock 2006-7, 2013-14.
  2. // Copyright Paul A. Bristow 2007, 2013-14.
  3. // Copyright Nikhar Agrawal 2013-14
  4. // Copyright Christopher Kormanyos 2013-14
  5. // Use, modification and distribution are subject to the
  6. // Boost Software License, Version 1.0. (See accompanying file
  7. // 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
  10. #ifdef _MSC_VER
  11. #pragma once
  12. #endif
  13. #include <boost/config.hpp>
  14. #include <boost/math/tools/series.hpp>
  15. #include <boost/math/tools/fraction.hpp>
  16. #include <boost/math/tools/precision.hpp>
  17. #include <boost/math/tools/promotion.hpp>
  18. #include <boost/math/policies/error_handling.hpp>
  19. #include <boost/math/constants/constants.hpp>
  20. #include <boost/math/special_functions/math_fwd.hpp>
  21. #include <boost/math/special_functions/log1p.hpp>
  22. #include <boost/math/special_functions/trunc.hpp>
  23. #include <boost/math/special_functions/powm1.hpp>
  24. #include <boost/math/special_functions/sqrt1pm1.hpp>
  25. #include <boost/math/special_functions/lanczos.hpp>
  26. #include <boost/math/special_functions/fpclassify.hpp>
  27. #include <boost/math/special_functions/detail/igamma_large.hpp>
  28. #include <boost/math/special_functions/detail/unchecked_factorial.hpp>
  29. #include <boost/math/special_functions/detail/lgamma_small.hpp>
  30. #include <boost/math/special_functions/bernoulli.hpp>
  31. #include <boost/math/special_functions/polygamma.hpp>
  32. #include <boost/type_traits/is_convertible.hpp>
  33. #include <boost/assert.hpp>
  34. #include <boost/mpl/greater.hpp>
  35. #include <boost/mpl/equal_to.hpp>
  36. #include <boost/mpl/greater.hpp>
  37. #include <boost/config/no_tr1/cmath.hpp>
  38. #include <algorithm>
  39. #ifdef BOOST_MSVC
  40. # pragma warning(push)
  41. # pragma warning(disable: 4702) // unreachable code (return after domain_error throw).
  42. # pragma warning(disable: 4127) // conditional expression is constant.
  43. # pragma warning(disable: 4100) // unreferenced formal parameter.
  44. // Several variables made comments,
  45. // but some difficulty as whether referenced on not may depend on macro values.
  46. // So to be safe, 4100 warnings suppressed.
  47. // TODO - revisit this?
  48. #endif
  49. namespace boost{ namespace math{
  50. namespace detail{
  51. template <class T>
  52. inline bool is_odd(T v, const boost::true_type&)
  53. {
  54. int i = static_cast<int>(v);
  55. return i&1;
  56. }
  57. template <class T>
  58. inline bool is_odd(T v, const boost::false_type&)
  59. {
  60. // Oh dear can't cast T to int!
  61. BOOST_MATH_STD_USING
  62. T modulus = v - 2 * floor(v/2);
  63. return static_cast<bool>(modulus != 0);
  64. }
  65. template <class T>
  66. inline bool is_odd(T v)
  67. {
  68. return is_odd(v, ::boost::is_convertible<T, int>());
  69. }
  70. template <class T>
  71. T sinpx(T z)
  72. {
  73. // Ad hoc function calculates x * sin(pi * x),
  74. // taking extra care near when x is near a whole number.
  75. BOOST_MATH_STD_USING
  76. int sign = 1;
  77. if(z < 0)
  78. {
  79. z = -z;
  80. }
  81. T fl = floor(z);
  82. T dist;
  83. if(is_odd(fl))
  84. {
  85. fl += 1;
  86. dist = fl - z;
  87. sign = -sign;
  88. }
  89. else
  90. {
  91. dist = z - fl;
  92. }
  93. BOOST_ASSERT(fl >= 0);
  94. if(dist > 0.5)
  95. dist = 1 - dist;
  96. T result = sin(dist*boost::math::constants::pi<T>());
  97. return sign*z*result;
  98. } // template <class T> T sinpx(T z)
  99. //
  100. // tgamma(z), with Lanczos support:
  101. //
  102. template <class T, class Policy, class Lanczos>
  103. T gamma_imp(T z, const Policy& pol, const Lanczos& l)
  104. {
  105. BOOST_MATH_STD_USING
  106. T result = 1;
  107. #ifdef BOOST_MATH_INSTRUMENT
  108. static bool b = false;
  109. if(!b)
  110. {
  111. std::cout << "tgamma_imp called with " << typeid(z).name() << " " << typeid(l).name() << std::endl;
  112. b = true;
  113. }
  114. #endif
  115. static const char* function = "boost::math::tgamma<%1%>(%1%)";
  116. if(z <= 0)
  117. {
  118. if(floor(z) == z)
  119. return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
  120. if(z <= -20)
  121. {
  122. result = gamma_imp(T(-z), pol, l) * sinpx(z);
  123. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  124. if((fabs(result) < 1) && (tools::max_value<T>() * fabs(result) < boost::math::constants::pi<T>()))
  125. return -boost::math::sign(result) * policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
  126. result = -boost::math::constants::pi<T>() / result;
  127. if(result == 0)
  128. return policies::raise_underflow_error<T>(function, "Result of tgamma is too small to represent.", pol);
  129. if((boost::math::fpclassify)(result) == (int)FP_SUBNORMAL)
  130. return policies::raise_denorm_error<T>(function, "Result of tgamma is denormalized.", result, pol);
  131. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  132. return result;
  133. }
  134. // shift z to > 1:
  135. while(z < 0)
  136. {
  137. result /= z;
  138. z += 1;
  139. }
  140. }
  141. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  142. if((floor(z) == z) && (z < max_factorial<T>::value))
  143. {
  144. result *= unchecked_factorial<T>(itrunc(z, pol) - 1);
  145. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  146. }
  147. else if (z < tools::root_epsilon<T>())
  148. {
  149. if (z < 1 / tools::max_value<T>())
  150. result = policies::raise_overflow_error<T>(function, 0, pol);
  151. result *= 1 / z - constants::euler<T>();
  152. }
  153. else
  154. {
  155. result *= Lanczos::lanczos_sum(z);
  156. T zgh = (z + static_cast<T>(Lanczos::g()) - boost::math::constants::half<T>());
  157. T lzgh = log(zgh);
  158. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  159. BOOST_MATH_INSTRUMENT_VARIABLE(tools::log_max_value<T>());
  160. if(z * lzgh > tools::log_max_value<T>())
  161. {
  162. // we're going to overflow unless this is done with care:
  163. BOOST_MATH_INSTRUMENT_VARIABLE(zgh);
  164. if(lzgh * z / 2 > tools::log_max_value<T>())
  165. return boost::math::sign(result) * policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
  166. T hp = pow(zgh, (z / 2) - T(0.25));
  167. BOOST_MATH_INSTRUMENT_VARIABLE(hp);
  168. result *= hp / exp(zgh);
  169. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  170. if(tools::max_value<T>() / hp < result)
  171. return boost::math::sign(result) * policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
  172. result *= hp;
  173. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  174. }
  175. else
  176. {
  177. BOOST_MATH_INSTRUMENT_VARIABLE(zgh);
  178. BOOST_MATH_INSTRUMENT_VARIABLE(pow(zgh, z - boost::math::constants::half<T>()));
  179. BOOST_MATH_INSTRUMENT_VARIABLE(exp(zgh));
  180. result *= pow(zgh, z - boost::math::constants::half<T>()) / exp(zgh);
  181. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  182. }
  183. }
  184. return result;
  185. }
  186. //
  187. // lgamma(z) with Lanczos support:
  188. //
  189. template <class T, class Policy, class Lanczos>
  190. T lgamma_imp(T z, const Policy& pol, const Lanczos& l, int* sign = 0)
  191. {
  192. #ifdef BOOST_MATH_INSTRUMENT
  193. static bool b = false;
  194. if(!b)
  195. {
  196. std::cout << "lgamma_imp called with " << typeid(z).name() << " " << typeid(l).name() << std::endl;
  197. b = true;
  198. }
  199. #endif
  200. BOOST_MATH_STD_USING
  201. static const char* function = "boost::math::lgamma<%1%>(%1%)";
  202. T result = 0;
  203. int sresult = 1;
  204. if(z <= -tools::root_epsilon<T>())
  205. {
  206. // reflection formula:
  207. if(floor(z) == z)
  208. return policies::raise_pole_error<T>(function, "Evaluation of lgamma at a negative integer %1%.", z, pol);
  209. T t = sinpx(z);
  210. z = -z;
  211. if(t < 0)
  212. {
  213. t = -t;
  214. }
  215. else
  216. {
  217. sresult = -sresult;
  218. }
  219. result = log(boost::math::constants::pi<T>()) - lgamma_imp(z, pol, l) - log(t);
  220. }
  221. else if (z < tools::root_epsilon<T>())
  222. {
  223. if (0 == z)
  224. return policies::raise_pole_error<T>(function, "Evaluation of lgamma at %1%.", z, pol);
  225. if (fabs(z) < 1 / tools::max_value<T>())
  226. result = -log(fabs(z));
  227. else
  228. result = log(fabs(1 / z - constants::euler<T>()));
  229. if (z < 0)
  230. sresult = -1;
  231. }
  232. else if(z < 15)
  233. {
  234. typedef typename policies::precision<T, Policy>::type precision_type;
  235. typedef typename mpl::if_<
  236. mpl::and_<
  237. mpl::less_equal<precision_type, mpl::int_<64> >,
  238. mpl::greater<precision_type, mpl::int_<0> >
  239. >,
  240. mpl::int_<64>,
  241. typename mpl::if_<
  242. mpl::and_<
  243. mpl::less_equal<precision_type, mpl::int_<113> >,
  244. mpl::greater<precision_type, mpl::int_<0> >
  245. >,
  246. mpl::int_<113>, mpl::int_<0> >::type
  247. >::type tag_type;
  248. result = lgamma_small_imp<T>(z, T(z - 1), T(z - 2), tag_type(), pol, l);
  249. }
  250. else if((z >= 3) && (z < 100) && (std::numeric_limits<T>::max_exponent >= 1024))
  251. {
  252. // taking the log of tgamma reduces the error, no danger of overflow here:
  253. result = log(gamma_imp(z, pol, l));
  254. }
  255. else
  256. {
  257. // regular evaluation:
  258. T zgh = static_cast<T>(z + Lanczos::g() - boost::math::constants::half<T>());
  259. result = log(zgh) - 1;
  260. result *= z - 0.5f;
  261. //
  262. // Only add on the lanczos sum part if we're going to need it:
  263. //
  264. if(result * tools::epsilon<T>() < 20)
  265. result += log(Lanczos::lanczos_sum_expG_scaled(z));
  266. }
  267. if(sign)
  268. *sign = sresult;
  269. return result;
  270. }
  271. //
  272. // Incomplete gamma functions follow:
  273. //
  274. template <class T>
  275. struct upper_incomplete_gamma_fract
  276. {
  277. private:
  278. T z, a;
  279. int k;
  280. public:
  281. typedef std::pair<T,T> result_type;
  282. upper_incomplete_gamma_fract(T a1, T z1)
  283. : z(z1-a1+1), a(a1), k(0)
  284. {
  285. }
  286. result_type operator()()
  287. {
  288. ++k;
  289. z += 2;
  290. return result_type(k * (a - k), z);
  291. }
  292. };
  293. template <class T>
  294. inline T upper_gamma_fraction(T a, T z, T eps)
  295. {
  296. // Multiply result by z^a * e^-z to get the full
  297. // upper incomplete integral. Divide by tgamma(z)
  298. // to normalise.
  299. upper_incomplete_gamma_fract<T> f(a, z);
  300. return 1 / (z - a + 1 + boost::math::tools::continued_fraction_a(f, eps));
  301. }
  302. template <class T>
  303. struct lower_incomplete_gamma_series
  304. {
  305. private:
  306. T a, z, result;
  307. public:
  308. typedef T result_type;
  309. lower_incomplete_gamma_series(T a1, T z1) : a(a1), z(z1), result(1){}
  310. T operator()()
  311. {
  312. T r = result;
  313. a += 1;
  314. result *= z/a;
  315. return r;
  316. }
  317. };
  318. template <class T, class Policy>
  319. inline T lower_gamma_series(T a, T z, const Policy& pol, T init_value = 0)
  320. {
  321. // Multiply result by ((z^a) * (e^-z) / a) to get the full
  322. // lower incomplete integral. Then divide by tgamma(a)
  323. // to get the normalised value.
  324. lower_incomplete_gamma_series<T> s(a, z);
  325. boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
  326. T factor = policies::get_epsilon<T, Policy>();
  327. T result = boost::math::tools::sum_series(s, factor, max_iter, init_value);
  328. policies::check_series_iterations<T>("boost::math::detail::lower_gamma_series<%1%>(%1%)", max_iter, pol);
  329. return result;
  330. }
  331. //
  332. // Fully generic tgamma and lgamma use Stirling's approximation
  333. // with Bernoulli numbers.
  334. //
  335. template<class T>
  336. std::size_t highest_bernoulli_index()
  337. {
  338. const float digits10_of_type = (std::numeric_limits<T>::is_specialized
  339. ? static_cast<float>(std::numeric_limits<T>::digits10)
  340. : static_cast<float>(boost::math::tools::digits<T>() * 0.301F));
  341. // Find the high index n for Bn to produce the desired precision in Stirling's calculation.
  342. return static_cast<std::size_t>(18.0F + (0.6F * digits10_of_type));
  343. }
  344. template<class T>
  345. int minimum_argument_for_bernoulli_recursion()
  346. {
  347. const float digits10_of_type = (std::numeric_limits<T>::is_specialized
  348. ? static_cast<float>(std::numeric_limits<T>::digits10)
  349. : static_cast<float>(boost::math::tools::digits<T>() * 0.301F));
  350. const float limit = std::ceil(std::pow(1.0f / std::ldexp(1.0f, 1-boost::math::tools::digits<T>()), 1.0f / 20.0f));
  351. return (int)((std::min)(digits10_of_type * 1.7F, limit));
  352. }
  353. template <class T, class Policy>
  354. T scaled_tgamma_no_lanczos(const T& z, const Policy& pol, bool islog = false)
  355. {
  356. BOOST_MATH_STD_USING
  357. //
  358. // Calculates tgamma(z) / (z/e)^z
  359. // Requires that our argument is large enough for Sterling's approximation to hold.
  360. // Used internally when combining gamma's of similar magnitude without logarithms.
  361. //
  362. BOOST_ASSERT(minimum_argument_for_bernoulli_recursion<T>() <= z);
  363. // Perform the Bernoulli series expansion of Stirling's approximation.
  364. const std::size_t number_of_bernoullis_b2n = policies::get_max_series_iterations<Policy>();
  365. T one_over_x_pow_two_n_minus_one = 1 / z;
  366. const T one_over_x2 = one_over_x_pow_two_n_minus_one * one_over_x_pow_two_n_minus_one;
  367. T sum = (boost::math::bernoulli_b2n<T>(1) / 2) * one_over_x_pow_two_n_minus_one;
  368. const T target_epsilon_to_break_loop = sum * boost::math::tools::epsilon<T>();
  369. const T half_ln_two_pi_over_z = sqrt(boost::math::constants::two_pi<T>() / z);
  370. T last_term = 2 * sum;
  371. for (std::size_t n = 2U;; ++n)
  372. {
  373. one_over_x_pow_two_n_minus_one *= one_over_x2;
  374. const std::size_t n2 = static_cast<std::size_t>(n * 2U);
  375. const T term = (boost::math::bernoulli_b2n<T>(static_cast<int>(n)) * one_over_x_pow_two_n_minus_one) / (n2 * (n2 - 1U));
  376. if ((n >= 3U) && (abs(term) < target_epsilon_to_break_loop))
  377. {
  378. // We have reached the desired precision in Stirling's expansion.
  379. // Adding additional terms to the sum of this divergent asymptotic
  380. // expansion will not improve the result.
  381. // Break from the loop.
  382. break;
  383. }
  384. if (n > number_of_bernoullis_b2n)
  385. 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);
  386. sum += term;
  387. // Sanity check for divergence:
  388. T fterm = fabs(term);
  389. if(fterm > last_term)
  390. 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);
  391. last_term = fterm;
  392. }
  393. // Complete Stirling's approximation.
  394. T scaled_gamma_value = islog ? T(sum + log(half_ln_two_pi_over_z)) : T(exp(sum) * half_ln_two_pi_over_z);
  395. return scaled_gamma_value;
  396. }
  397. // Forward declaration of the lgamma_imp template specialization.
  398. template <class T, class Policy>
  399. T lgamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos&, int* sign = 0);
  400. template <class T, class Policy>
  401. T gamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos&)
  402. {
  403. BOOST_MATH_STD_USING
  404. static const char* function = "boost::math::tgamma<%1%>(%1%)";
  405. // Check if the argument of tgamma is identically zero.
  406. const bool is_at_zero = (z == 0);
  407. if((boost::math::isnan)(z) || (is_at_zero) || ((boost::math::isinf)(z) && (z < 0)))
  408. return policies::raise_domain_error<T>(function, "Evaluation of tgamma at %1%.", z, pol);
  409. const bool b_neg = (z < 0);
  410. const bool floor_of_z_is_equal_to_z = (floor(z) == z);
  411. // Special case handling of small factorials:
  412. if((!b_neg) && floor_of_z_is_equal_to_z && (z < boost::math::max_factorial<T>::value))
  413. {
  414. return boost::math::unchecked_factorial<T>(itrunc(z) - 1);
  415. }
  416. // Make a local, unsigned copy of the input argument.
  417. T zz((!b_neg) ? z : -z);
  418. // Special case for ultra-small z:
  419. if(zz < tools::cbrt_epsilon<T>())
  420. {
  421. const T a0(1);
  422. const T a1(boost::math::constants::euler<T>());
  423. const T six_euler_squared((boost::math::constants::euler<T>() * boost::math::constants::euler<T>()) * 6);
  424. const T a2((six_euler_squared - boost::math::constants::pi_sqr<T>()) / 12);
  425. const T inverse_tgamma_series = z * ((a2 * z + a1) * z + a0);
  426. return 1 / inverse_tgamma_series;
  427. }
  428. // Scale the argument up for the calculation of lgamma,
  429. // and use downward recursion later for the final result.
  430. const int min_arg_for_recursion = minimum_argument_for_bernoulli_recursion<T>();
  431. int n_recur;
  432. if(zz < min_arg_for_recursion)
  433. {
  434. n_recur = boost::math::itrunc(min_arg_for_recursion - zz) + 1;
  435. zz += n_recur;
  436. }
  437. else
  438. {
  439. n_recur = 0;
  440. }
  441. if (!n_recur)
  442. {
  443. if (zz > tools::log_max_value<T>())
  444. return policies::raise_overflow_error<T>(function, 0, pol);
  445. if (log(zz) * zz / 2 > tools::log_max_value<T>())
  446. return policies::raise_overflow_error<T>(function, 0, pol);
  447. }
  448. T gamma_value = scaled_tgamma_no_lanczos(zz, pol);
  449. T power_term = pow(zz, zz / 2);
  450. T exp_term = exp(-zz);
  451. gamma_value *= (power_term * exp_term);
  452. if(!n_recur && (tools::max_value<T>() / power_term < gamma_value))
  453. return policies::raise_overflow_error<T>(function, 0, pol);
  454. gamma_value *= power_term;
  455. // Rescale the result using downward recursion if necessary.
  456. if(n_recur)
  457. {
  458. // The order of divides is important, if we keep subtracting 1 from zz
  459. // we DO NOT get back to z (cancellation error). Further if z < epsilon
  460. // we would end up dividing by zero. Also in order to prevent spurious
  461. // overflow with the first division, we must save dividing by |z| till last,
  462. // so the optimal order of divides is z+1, z+2, z+3...z+n_recur-1,z.
  463. zz = fabs(z) + 1;
  464. for(int k = 1; k < n_recur; ++k)
  465. {
  466. gamma_value /= zz;
  467. zz += 1;
  468. }
  469. gamma_value /= fabs(z);
  470. }
  471. // Return the result, accounting for possible negative arguments.
  472. if(b_neg)
  473. {
  474. // Provide special error analysis for:
  475. // * arguments in the neighborhood of a negative integer
  476. // * arguments exactly equal to a negative integer.
  477. // Check if the argument of tgamma is exactly equal to a negative integer.
  478. if(floor_of_z_is_equal_to_z)
  479. return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
  480. gamma_value *= sinpx(z);
  481. BOOST_MATH_INSTRUMENT_VARIABLE(gamma_value);
  482. const bool result_is_too_large_to_represent = ( (abs(gamma_value) < 1)
  483. && ((tools::max_value<T>() * abs(gamma_value)) < boost::math::constants::pi<T>()));
  484. if(result_is_too_large_to_represent)
  485. return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
  486. gamma_value = -boost::math::constants::pi<T>() / gamma_value;
  487. BOOST_MATH_INSTRUMENT_VARIABLE(gamma_value);
  488. if(gamma_value == 0)
  489. return policies::raise_underflow_error<T>(function, "Result of tgamma is too small to represent.", pol);
  490. if((boost::math::fpclassify)(gamma_value) == static_cast<int>(FP_SUBNORMAL))
  491. return policies::raise_denorm_error<T>(function, "Result of tgamma is denormalized.", gamma_value, pol);
  492. }
  493. return gamma_value;
  494. }
  495. template <class T, class Policy>
  496. inline T log_gamma_near_1(const T& z, Policy const& pol)
  497. {
  498. //
  499. // This is for the multiprecision case where there is
  500. // no lanczos support, use a taylor series at z = 1,
  501. // see https://www.wolframalpha.com/input/?i=taylor+series+lgamma(x)+at+x+%3D+1
  502. //
  503. BOOST_MATH_STD_USING // ADL of std names
  504. BOOST_ASSERT(fabs(z) < 1);
  505. T result = -constants::euler<T>() * z;
  506. T power_term = z * z / 2;
  507. int n = 2;
  508. T term = 0;
  509. do
  510. {
  511. term = power_term * boost::math::polygamma(n - 1, T(1));
  512. result += term;
  513. ++n;
  514. power_term *= z / n;
  515. } while (fabs(result) * tools::epsilon<T>() < fabs(term));
  516. return result;
  517. }
  518. template <class T, class Policy>
  519. T lgamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos&, int* sign)
  520. {
  521. BOOST_MATH_STD_USING
  522. static const char* function = "boost::math::lgamma<%1%>(%1%)";
  523. // Check if the argument of lgamma is identically zero.
  524. const bool is_at_zero = (z == 0);
  525. if(is_at_zero)
  526. return policies::raise_domain_error<T>(function, "Evaluation of lgamma at zero %1%.", z, pol);
  527. if((boost::math::isnan)(z))
  528. return policies::raise_domain_error<T>(function, "Evaluation of lgamma at %1%.", z, pol);
  529. if((boost::math::isinf)(z))
  530. return policies::raise_overflow_error<T>(function, 0, pol);
  531. const bool b_neg = (z < 0);
  532. const bool floor_of_z_is_equal_to_z = (floor(z) == z);
  533. // Special case handling of small factorials:
  534. if((!b_neg) && floor_of_z_is_equal_to_z && (z < boost::math::max_factorial<T>::value))
  535. {
  536. if (sign)
  537. *sign = 1;
  538. return log(boost::math::unchecked_factorial<T>(itrunc(z) - 1));
  539. }
  540. // Make a local, unsigned copy of the input argument.
  541. T zz((!b_neg) ? z : -z);
  542. const int min_arg_for_recursion = minimum_argument_for_bernoulli_recursion<T>();
  543. T log_gamma_value;
  544. if (zz < min_arg_for_recursion)
  545. {
  546. // Here we simply take the logarithm of tgamma(). This is somewhat
  547. // inefficient, but simple. The rationale is that the argument here
  548. // is relatively small and overflow is not expected to be likely.
  549. if (sign)
  550. * sign = 1;
  551. if(fabs(z - 1) < 0.25)
  552. {
  553. log_gamma_value = log_gamma_near_1(T(zz - 1), pol);
  554. }
  555. else if(fabs(z - 2) < 0.25)
  556. {
  557. log_gamma_value = log_gamma_near_1(T(zz - 2), pol) + log(zz - 1);
  558. }
  559. else if (z > -tools::root_epsilon<T>())
  560. {
  561. // Reflection formula may fail if z is very close to zero, let the series
  562. // expansion for tgamma close to zero do the work:
  563. if (sign)
  564. *sign = z < 0 ? -1 : 1;
  565. return log(abs(gamma_imp(z, pol, lanczos::undefined_lanczos())));
  566. }
  567. else
  568. {
  569. // No issue with spurious overflow in reflection formula,
  570. // just fall through to regular code:
  571. T g = gamma_imp(zz, pol, lanczos::undefined_lanczos());
  572. if (sign)
  573. {
  574. *sign = g < 0 ? -1 : 1;
  575. }
  576. log_gamma_value = log(abs(g));
  577. }
  578. }
  579. else
  580. {
  581. // Perform the Bernoulli series expansion of Stirling's approximation.
  582. T sum = scaled_tgamma_no_lanczos(zz, pol, true);
  583. log_gamma_value = zz * (log(zz) - 1) + sum;
  584. }
  585. int sign_of_result = 1;
  586. if(b_neg)
  587. {
  588. // Provide special error analysis if the argument is exactly
  589. // equal to a negative integer.
  590. // Check if the argument of lgamma is exactly equal to a negative integer.
  591. if(floor_of_z_is_equal_to_z)
  592. return policies::raise_pole_error<T>(function, "Evaluation of lgamma at a negative integer %1%.", z, pol);
  593. T t = sinpx(z);
  594. if(t < 0)
  595. {
  596. t = -t;
  597. }
  598. else
  599. {
  600. sign_of_result = -sign_of_result;
  601. }
  602. log_gamma_value = - log_gamma_value
  603. + log(boost::math::constants::pi<T>())
  604. - log(t);
  605. }
  606. if(sign != static_cast<int*>(0U)) { *sign = sign_of_result; }
  607. return log_gamma_value;
  608. }
  609. //
  610. // This helper calculates tgamma(dz+1)-1 without cancellation errors,
  611. // used by the upper incomplete gamma with z < 1:
  612. //
  613. template <class T, class Policy, class Lanczos>
  614. T tgammap1m1_imp(T dz, Policy const& pol, const Lanczos& l)
  615. {
  616. BOOST_MATH_STD_USING
  617. typedef typename policies::precision<T,Policy>::type precision_type;
  618. typedef typename mpl::if_<
  619. mpl::or_<
  620. mpl::less_equal<precision_type, mpl::int_<0> >,
  621. mpl::greater<precision_type, mpl::int_<113> >
  622. >,
  623. typename mpl::if_<
  624. mpl::and_<is_same<Lanczos, lanczos::lanczos24m113>, mpl::greater<precision_type, mpl::int_<0> > >,
  625. mpl::int_<113>,
  626. mpl::int_<0>
  627. >::type,
  628. typename mpl::if_<
  629. mpl::less_equal<precision_type, mpl::int_<64> >,
  630. mpl::int_<64>, mpl::int_<113> >::type
  631. >::type tag_type;
  632. T result;
  633. if(dz < 0)
  634. {
  635. if(dz < -0.5)
  636. {
  637. // Best method is simply to subtract 1 from tgamma:
  638. result = boost::math::tgamma(1+dz, pol) - 1;
  639. BOOST_MATH_INSTRUMENT_CODE(result);
  640. }
  641. else
  642. {
  643. // Use expm1 on lgamma:
  644. result = boost::math::expm1(-boost::math::log1p(dz, pol)
  645. + lgamma_small_imp<T>(dz+2, dz + 1, dz, tag_type(), pol, l));
  646. BOOST_MATH_INSTRUMENT_CODE(result);
  647. }
  648. }
  649. else
  650. {
  651. if(dz < 2)
  652. {
  653. // Use expm1 on lgamma:
  654. result = boost::math::expm1(lgamma_small_imp<T>(dz+1, dz, dz-1, tag_type(), pol, l), pol);
  655. BOOST_MATH_INSTRUMENT_CODE(result);
  656. }
  657. else
  658. {
  659. // Best method is simply to subtract 1 from tgamma:
  660. result = boost::math::tgamma(1+dz, pol) - 1;
  661. BOOST_MATH_INSTRUMENT_CODE(result);
  662. }
  663. }
  664. return result;
  665. }
  666. template <class T, class Policy>
  667. inline T tgammap1m1_imp(T z, Policy const& pol,
  668. const ::boost::math::lanczos::undefined_lanczos&)
  669. {
  670. BOOST_MATH_STD_USING // ADL of std names
  671. if(fabs(z) < 0.55)
  672. {
  673. return boost::math::expm1(log_gamma_near_1(z, pol));
  674. }
  675. return boost::math::expm1(boost::math::lgamma(1 + z, pol));
  676. }
  677. //
  678. // Series representation for upper fraction when z is small:
  679. //
  680. template <class T>
  681. struct small_gamma2_series
  682. {
  683. typedef T result_type;
  684. small_gamma2_series(T a_, T x_) : result(-x_), x(-x_), apn(a_+1), n(1){}
  685. T operator()()
  686. {
  687. T r = result / (apn);
  688. result *= x;
  689. result /= ++n;
  690. apn += 1;
  691. return r;
  692. }
  693. private:
  694. T result, x, apn;
  695. int n;
  696. };
  697. //
  698. // calculate power term prefix (z^a)(e^-z) used in the non-normalised
  699. // incomplete gammas:
  700. //
  701. template <class T, class Policy>
  702. T full_igamma_prefix(T a, T z, const Policy& pol)
  703. {
  704. BOOST_MATH_STD_USING
  705. T prefix;
  706. if (z > tools::max_value<T>())
  707. return 0;
  708. T alz = a * log(z);
  709. if(z >= 1)
  710. {
  711. if((alz < tools::log_max_value<T>()) && (-z > tools::log_min_value<T>()))
  712. {
  713. prefix = pow(z, a) * exp(-z);
  714. }
  715. else if(a >= 1)
  716. {
  717. prefix = pow(z / exp(z/a), a);
  718. }
  719. else
  720. {
  721. prefix = exp(alz - z);
  722. }
  723. }
  724. else
  725. {
  726. if(alz > tools::log_min_value<T>())
  727. {
  728. prefix = pow(z, a) * exp(-z);
  729. }
  730. else if(z/a < tools::log_max_value<T>())
  731. {
  732. prefix = pow(z / exp(z/a), a);
  733. }
  734. else
  735. {
  736. prefix = exp(alz - z);
  737. }
  738. }
  739. //
  740. // This error handling isn't very good: it happens after the fact
  741. // rather than before it...
  742. //
  743. if((boost::math::fpclassify)(prefix) == (int)FP_INFINITE)
  744. 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);
  745. return prefix;
  746. }
  747. //
  748. // Compute (z^a)(e^-z)/tgamma(a)
  749. // most if the error occurs in this function:
  750. //
  751. template <class T, class Policy, class Lanczos>
  752. T regularised_gamma_prefix(T a, T z, const Policy& pol, const Lanczos& l)
  753. {
  754. BOOST_MATH_STD_USING
  755. if (z >= tools::max_value<T>())
  756. return 0;
  757. T agh = a + static_cast<T>(Lanczos::g()) - T(0.5);
  758. T prefix;
  759. T d = ((z - a) - static_cast<T>(Lanczos::g()) + T(0.5)) / agh;
  760. if(a < 1)
  761. {
  762. //
  763. // We have to treat a < 1 as a special case because our Lanczos
  764. // approximations are optimised against the factorials with a > 1,
  765. // and for high precision types especially (128-bit reals for example)
  766. // very small values of a can give rather eroneous results for gamma
  767. // unless we do this:
  768. //
  769. // TODO: is this still required? Lanczos approx should be better now?
  770. //
  771. if(z <= tools::log_min_value<T>())
  772. {
  773. // Oh dear, have to use logs, should be free of cancellation errors though:
  774. return exp(a * log(z) - z - lgamma_imp(a, pol, l));
  775. }
  776. else
  777. {
  778. // direct calculation, no danger of overflow as gamma(a) < 1/a
  779. // for small a.
  780. return pow(z, a) * exp(-z) / gamma_imp(a, pol, l);
  781. }
  782. }
  783. else if((fabs(d*d*a) <= 100) && (a > 150))
  784. {
  785. // special case for large a and a ~ z.
  786. prefix = a * boost::math::log1pmx(d, pol) + z * static_cast<T>(0.5 - Lanczos::g()) / agh;
  787. prefix = exp(prefix);
  788. }
  789. else
  790. {
  791. //
  792. // general case.
  793. // direct computation is most accurate, but use various fallbacks
  794. // for different parts of the problem domain:
  795. //
  796. T alz = a * log(z / agh);
  797. T amz = a - z;
  798. if(((std::min)(alz, amz) <= tools::log_min_value<T>()) || ((std::max)(alz, amz) >= tools::log_max_value<T>()))
  799. {
  800. T amza = amz / a;
  801. if(((std::min)(alz, amz)/2 > tools::log_min_value<T>()) && ((std::max)(alz, amz)/2 < tools::log_max_value<T>()))
  802. {
  803. // compute square root of the result and then square it:
  804. T sq = pow(z / agh, a / 2) * exp(amz / 2);
  805. prefix = sq * sq;
  806. }
  807. else if(((std::min)(alz, amz)/4 > tools::log_min_value<T>()) && ((std::max)(alz, amz)/4 < tools::log_max_value<T>()) && (z > a))
  808. {
  809. // compute the 4th root of the result then square it twice:
  810. T sq = pow(z / agh, a / 4) * exp(amz / 4);
  811. prefix = sq * sq;
  812. prefix *= prefix;
  813. }
  814. else if((amza > tools::log_min_value<T>()) && (amza < tools::log_max_value<T>()))
  815. {
  816. prefix = pow((z * exp(amza)) / agh, a);
  817. }
  818. else
  819. {
  820. prefix = exp(alz + amz);
  821. }
  822. }
  823. else
  824. {
  825. prefix = pow(z / agh, a) * exp(amz);
  826. }
  827. }
  828. prefix *= sqrt(agh / boost::math::constants::e<T>()) / Lanczos::lanczos_sum_expG_scaled(a);
  829. return prefix;
  830. }
  831. //
  832. // And again, without Lanczos support:
  833. //
  834. template <class T, class Policy>
  835. T regularised_gamma_prefix(T a, T z, const Policy& pol, const lanczos::undefined_lanczos& l)
  836. {
  837. BOOST_MATH_STD_USING
  838. if((a < 1) && (z < 1))
  839. {
  840. // No overflow possible since the power terms tend to unity as a,z -> 0
  841. return pow(z, a) * exp(-z) / boost::math::tgamma(a, pol);
  842. }
  843. else if(a > minimum_argument_for_bernoulli_recursion<T>())
  844. {
  845. T scaled_gamma = scaled_tgamma_no_lanczos(a, pol);
  846. T power_term = pow(z / a, a / 2);
  847. T a_minus_z = a - z;
  848. if ((0 == power_term) || (fabs(a_minus_z) > tools::log_max_value<T>()))
  849. {
  850. // The result is probably zero, but we need to be sure:
  851. return exp(a * log(z / a) + a_minus_z - log(scaled_gamma));
  852. }
  853. return (power_term * exp(a_minus_z)) * (power_term / scaled_gamma);
  854. }
  855. else
  856. {
  857. //
  858. // Usual case is to calculate the prefix at a+shift and recurse down
  859. // to the value we want:
  860. //
  861. const int min_z = minimum_argument_for_bernoulli_recursion<T>();
  862. long shift = 1 + ltrunc(min_z - a);
  863. T result = regularised_gamma_prefix(T(a + shift), z, pol, l);
  864. if (result != 0)
  865. {
  866. for (long i = 0; i < shift; ++i)
  867. {
  868. result /= z;
  869. result *= a + i;
  870. }
  871. return result;
  872. }
  873. else
  874. {
  875. //
  876. // We failed, most probably we have z << 1, try again, this time
  877. // we calculate z^a e^-z / tgamma(a+shift), combining power terms
  878. // as we go. And again recurse down to the result.
  879. //
  880. T scaled_gamma = scaled_tgamma_no_lanczos(T(a + shift), pol);
  881. T power_term_1 = pow(z / (a + shift), a);
  882. T power_term_2 = pow(a + shift, -shift);
  883. T power_term_3 = exp(a + shift - z);
  884. if ((0 == power_term_1) || (0 == power_term_2) || (0 == power_term_3) || (fabs(a + shift - z) > tools::log_max_value<T>()))
  885. {
  886. // We have no test case that gets here, most likely the type T
  887. // has a high precision but low exponent range:
  888. return exp(a * log(z) - z - boost::math::lgamma(a, pol));
  889. }
  890. result = power_term_1 * power_term_2 * power_term_3 / scaled_gamma;
  891. for (long i = 0; i < shift; ++i)
  892. {
  893. result *= a + i;
  894. }
  895. return result;
  896. }
  897. }
  898. }
  899. //
  900. // Upper gamma fraction for very small a:
  901. //
  902. template <class T, class Policy>
  903. inline T tgamma_small_upper_part(T a, T x, const Policy& pol, T* pgam = 0, bool invert = false, T* pderivative = 0)
  904. {
  905. BOOST_MATH_STD_USING // ADL of std functions.
  906. //
  907. // Compute the full upper fraction (Q) when a is very small:
  908. //
  909. T result;
  910. result = boost::math::tgamma1pm1(a, pol);
  911. if(pgam)
  912. *pgam = (result + 1) / a;
  913. T p = boost::math::powm1(x, a, pol);
  914. result -= p;
  915. result /= a;
  916. detail::small_gamma2_series<T> s(a, x);
  917. boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>() - 10;
  918. p += 1;
  919. if(pderivative)
  920. *pderivative = p / (*pgam * exp(x));
  921. T init_value = invert ? *pgam : 0;
  922. result = -p * tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, (init_value - result) / p);
  923. policies::check_series_iterations<T>("boost::math::tgamma_small_upper_part<%1%>(%1%, %1%)", max_iter, pol);
  924. if(invert)
  925. result = -result;
  926. return result;
  927. }
  928. //
  929. // Upper gamma fraction for integer a:
  930. //
  931. template <class T, class Policy>
  932. inline T finite_gamma_q(T a, T x, Policy const& pol, T* pderivative = 0)
  933. {
  934. //
  935. // Calculates normalised Q when a is an integer:
  936. //
  937. BOOST_MATH_STD_USING
  938. T e = exp(-x);
  939. T sum = e;
  940. if(sum != 0)
  941. {
  942. T term = sum;
  943. for(unsigned n = 1; n < a; ++n)
  944. {
  945. term /= n;
  946. term *= x;
  947. sum += term;
  948. }
  949. }
  950. if(pderivative)
  951. {
  952. *pderivative = e * pow(x, a) / boost::math::unchecked_factorial<T>(itrunc(T(a - 1), pol));
  953. }
  954. return sum;
  955. }
  956. //
  957. // Upper gamma fraction for half integer a:
  958. //
  959. template <class T, class Policy>
  960. T finite_half_gamma_q(T a, T x, T* p_derivative, const Policy& pol)
  961. {
  962. //
  963. // Calculates normalised Q when a is a half-integer:
  964. //
  965. BOOST_MATH_STD_USING
  966. T e = boost::math::erfc(sqrt(x), pol);
  967. if((e != 0) && (a > 1))
  968. {
  969. T term = exp(-x) / sqrt(constants::pi<T>() * x);
  970. term *= x;
  971. static const T half = T(1) / 2;
  972. term /= half;
  973. T sum = term;
  974. for(unsigned n = 2; n < a; ++n)
  975. {
  976. term /= n - half;
  977. term *= x;
  978. sum += term;
  979. }
  980. e += sum;
  981. if(p_derivative)
  982. {
  983. *p_derivative = 0;
  984. }
  985. }
  986. else if(p_derivative)
  987. {
  988. // We'll be dividing by x later, so calculate derivative * x:
  989. *p_derivative = sqrt(x) * exp(-x) / constants::root_pi<T>();
  990. }
  991. return e;
  992. }
  993. //
  994. // Asymptotic approximation for large argument, see: https://dlmf.nist.gov/8.11#E2
  995. //
  996. template <class T>
  997. struct incomplete_tgamma_large_x_series
  998. {
  999. typedef T result_type;
  1000. incomplete_tgamma_large_x_series(const T& a, const T& x)
  1001. : a_poch(a - 1), z(x), term(1) {}
  1002. T operator()()
  1003. {
  1004. T result = term;
  1005. term *= a_poch / z;
  1006. a_poch -= 1;
  1007. return result;
  1008. }
  1009. T a_poch, z, term;
  1010. };
  1011. template <class T, class Policy>
  1012. T incomplete_tgamma_large_x(const T& a, const T& x, const Policy& pol)
  1013. {
  1014. BOOST_MATH_STD_USING
  1015. incomplete_tgamma_large_x_series<T> s(a, x);
  1016. boost::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<Policy>();
  1017. T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);
  1018. boost::math::policies::check_series_iterations<T>("boost::math::tgamma<%1%>(%1%,%1%)", max_iter, pol);
  1019. return result;
  1020. }
  1021. //
  1022. // Main incomplete gamma entry point, handles all four incomplete gamma's:
  1023. //
  1024. template <class T, class Policy>
  1025. T gamma_incomplete_imp(T a, T x, bool normalised, bool invert,
  1026. const Policy& pol, T* p_derivative)
  1027. {
  1028. static const char* function = "boost::math::gamma_p<%1%>(%1%, %1%)";
  1029. if(a <= 0)
  1030. return policies::raise_domain_error<T>(function, "Argument a to the incomplete gamma function must be greater than zero (got a=%1%).", a, pol);
  1031. if(x < 0)
  1032. return policies::raise_domain_error<T>(function, "Argument x to the incomplete gamma function must be >= 0 (got x=%1%).", x, pol);
  1033. BOOST_MATH_STD_USING
  1034. typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
  1035. T result = 0; // Just to avoid warning C4701: potentially uninitialized local variable 'result' used
  1036. if(a >= max_factorial<T>::value && !normalised)
  1037. {
  1038. //
  1039. // When we're computing the non-normalized incomplete gamma
  1040. // and a is large the result is rather hard to compute unless
  1041. // we use logs. There are really two options - if x is a long
  1042. // way from a in value then we can reliably use methods 2 and 4
  1043. // below in logarithmic form and go straight to the result.
  1044. // Otherwise we let the regularized gamma take the strain
  1045. // (the result is unlikely to unerflow in the central region anyway)
  1046. // and combine with lgamma in the hopes that we get a finite result.
  1047. //
  1048. if(invert && (a * 4 < x))
  1049. {
  1050. // This is method 4 below, done in logs:
  1051. result = a * log(x) - x;
  1052. if(p_derivative)
  1053. *p_derivative = exp(result);
  1054. result += log(upper_gamma_fraction(a, x, policies::get_epsilon<T, Policy>()));
  1055. }
  1056. else if(!invert && (a > 4 * x))
  1057. {
  1058. // This is method 2 below, done in logs:
  1059. result = a * log(x) - x;
  1060. if(p_derivative)
  1061. *p_derivative = exp(result);
  1062. T init_value = 0;
  1063. result += log(detail::lower_gamma_series(a, x, pol, init_value) / a);
  1064. }
  1065. else
  1066. {
  1067. result = gamma_incomplete_imp(a, x, true, invert, pol, p_derivative);
  1068. if(result == 0)
  1069. {
  1070. if(invert)
  1071. {
  1072. // Try http://functions.wolfram.com/06.06.06.0039.01
  1073. result = 1 + 1 / (12 * a) + 1 / (288 * a * a);
  1074. result = log(result) - a + (a - 0.5f) * log(a) + log(boost::math::constants::root_two_pi<T>());
  1075. if(p_derivative)
  1076. *p_derivative = exp(a * log(x) - x);
  1077. }
  1078. else
  1079. {
  1080. // This is method 2 below, done in logs, we're really outside the
  1081. // range of this method, but since the result is almost certainly
  1082. // infinite, we should probably be OK:
  1083. result = a * log(x) - x;
  1084. if(p_derivative)
  1085. *p_derivative = exp(result);
  1086. T init_value = 0;
  1087. result += log(detail::lower_gamma_series(a, x, pol, init_value) / a);
  1088. }
  1089. }
  1090. else
  1091. {
  1092. result = log(result) + boost::math::lgamma(a, pol);
  1093. }
  1094. }
  1095. if(result > tools::log_max_value<T>())
  1096. return policies::raise_overflow_error<T>(function, 0, pol);
  1097. return exp(result);
  1098. }
  1099. BOOST_ASSERT((p_derivative == 0) || (normalised == true));
  1100. bool is_int, is_half_int;
  1101. bool is_small_a = (a < 30) && (a <= x + 1) && (x < tools::log_max_value<T>());
  1102. if(is_small_a)
  1103. {
  1104. T fa = floor(a);
  1105. is_int = (fa == a);
  1106. is_half_int = is_int ? false : (fabs(fa - a) == 0.5f);
  1107. }
  1108. else
  1109. {
  1110. is_int = is_half_int = false;
  1111. }
  1112. int eval_method;
  1113. if(is_int && (x > 0.6))
  1114. {
  1115. // calculate Q via finite sum:
  1116. invert = !invert;
  1117. eval_method = 0;
  1118. }
  1119. else if(is_half_int && (x > 0.2))
  1120. {
  1121. // calculate Q via finite sum for half integer a:
  1122. invert = !invert;
  1123. eval_method = 1;
  1124. }
  1125. else if((x < tools::root_epsilon<T>()) && (a > 1))
  1126. {
  1127. eval_method = 6;
  1128. }
  1129. else if ((x > 1000) && ((a < x) || (fabs(a - 50) / x < 1)))
  1130. {
  1131. // calculate Q via asymptotic approximation:
  1132. invert = !invert;
  1133. eval_method = 7;
  1134. }
  1135. else if(x < 0.5)
  1136. {
  1137. //
  1138. // Changeover criterion chosen to give a changeover at Q ~ 0.33
  1139. //
  1140. if(-0.4 / log(x) < a)
  1141. {
  1142. eval_method = 2;
  1143. }
  1144. else
  1145. {
  1146. eval_method = 3;
  1147. }
  1148. }
  1149. else if(x < 1.1)
  1150. {
  1151. //
  1152. // Changover here occurs when P ~ 0.75 or Q ~ 0.25:
  1153. //
  1154. if(x * 0.75f < a)
  1155. {
  1156. eval_method = 2;
  1157. }
  1158. else
  1159. {
  1160. eval_method = 3;
  1161. }
  1162. }
  1163. else
  1164. {
  1165. //
  1166. // Begin by testing whether we're in the "bad" zone
  1167. // where the result will be near 0.5 and the usual
  1168. // series and continued fractions are slow to converge:
  1169. //
  1170. bool use_temme = false;
  1171. if(normalised && std::numeric_limits<T>::is_specialized && (a > 20))
  1172. {
  1173. T sigma = fabs((x-a)/a);
  1174. if((a > 200) && (policies::digits<T, Policy>() <= 113))
  1175. {
  1176. //
  1177. // This limit is chosen so that we use Temme's expansion
  1178. // only if the result would be larger than about 10^-6.
  1179. // Below that the regular series and continued fractions
  1180. // converge OK, and if we use Temme's method we get increasing
  1181. // errors from the dominant erfc term as it's (inexact) argument
  1182. // increases in magnitude.
  1183. //
  1184. if(20 / a > sigma * sigma)
  1185. use_temme = true;
  1186. }
  1187. else if(policies::digits<T, Policy>() <= 64)
  1188. {
  1189. // Note in this zone we can't use Temme's expansion for
  1190. // types longer than an 80-bit real:
  1191. // it would require too many terms in the polynomials.
  1192. if(sigma < 0.4)
  1193. use_temme = true;
  1194. }
  1195. }
  1196. if(use_temme)
  1197. {
  1198. eval_method = 5;
  1199. }
  1200. else
  1201. {
  1202. //
  1203. // Regular case where the result will not be too close to 0.5.
  1204. //
  1205. // Changeover here occurs at P ~ Q ~ 0.5
  1206. // Note that series computation of P is about x2 faster than continued fraction
  1207. // calculation of Q, so try and use the CF only when really necessary, especially
  1208. // for small x.
  1209. //
  1210. if(x - (1 / (3 * x)) < a)
  1211. {
  1212. eval_method = 2;
  1213. }
  1214. else
  1215. {
  1216. eval_method = 4;
  1217. invert = !invert;
  1218. }
  1219. }
  1220. }
  1221. switch(eval_method)
  1222. {
  1223. case 0:
  1224. {
  1225. result = finite_gamma_q(a, x, pol, p_derivative);
  1226. if(normalised == false)
  1227. result *= boost::math::tgamma(a, pol);
  1228. break;
  1229. }
  1230. case 1:
  1231. {
  1232. result = finite_half_gamma_q(a, x, p_derivative, pol);
  1233. if(normalised == false)
  1234. result *= boost::math::tgamma(a, pol);
  1235. if(p_derivative && (*p_derivative == 0))
  1236. *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
  1237. break;
  1238. }
  1239. case 2:
  1240. {
  1241. // Compute P:
  1242. result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
  1243. if(p_derivative)
  1244. *p_derivative = result;
  1245. if(result != 0)
  1246. {
  1247. //
  1248. // If we're going to be inverting the result then we can
  1249. // reduce the number of series evaluations by quite
  1250. // a few iterations if we set an initial value for the
  1251. // series sum based on what we'll end up subtracting it from
  1252. // at the end.
  1253. // Have to be careful though that this optimization doesn't
  1254. // lead to spurious numberic overflow. Note that the
  1255. // scary/expensive overflow checks below are more often
  1256. // than not bypassed in practice for "sensible" input
  1257. // values:
  1258. //
  1259. T init_value = 0;
  1260. bool optimised_invert = false;
  1261. if(invert)
  1262. {
  1263. init_value = (normalised ? 1 : boost::math::tgamma(a, pol));
  1264. if(normalised || (result >= 1) || (tools::max_value<T>() * result > init_value))
  1265. {
  1266. init_value /= result;
  1267. if(normalised || (a < 1) || (tools::max_value<T>() / a > init_value))
  1268. {
  1269. init_value *= -a;
  1270. optimised_invert = true;
  1271. }
  1272. else
  1273. init_value = 0;
  1274. }
  1275. else
  1276. init_value = 0;
  1277. }
  1278. result *= detail::lower_gamma_series(a, x, pol, init_value) / a;
  1279. if(optimised_invert)
  1280. {
  1281. invert = false;
  1282. result = -result;
  1283. }
  1284. }
  1285. break;
  1286. }
  1287. case 3:
  1288. {
  1289. // Compute Q:
  1290. invert = !invert;
  1291. T g;
  1292. result = tgamma_small_upper_part(a, x, pol, &g, invert, p_derivative);
  1293. invert = false;
  1294. if(normalised)
  1295. result /= g;
  1296. break;
  1297. }
  1298. case 4:
  1299. {
  1300. // Compute Q:
  1301. result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
  1302. if(p_derivative)
  1303. *p_derivative = result;
  1304. if(result != 0)
  1305. result *= upper_gamma_fraction(a, x, policies::get_epsilon<T, Policy>());
  1306. break;
  1307. }
  1308. case 5:
  1309. {
  1310. //
  1311. // Use compile time dispatch to the appropriate
  1312. // Temme asymptotic expansion. This may be dead code
  1313. // if T does not have numeric limits support, or has
  1314. // too many digits for the most precise version of
  1315. // these expansions, in that case we'll be calling
  1316. // an empty function.
  1317. //
  1318. typedef typename policies::precision<T, Policy>::type precision_type;
  1319. typedef typename mpl::if_<
  1320. mpl::or_<mpl::equal_to<precision_type, mpl::int_<0> >,
  1321. mpl::greater<precision_type, mpl::int_<113> > >,
  1322. mpl::int_<0>,
  1323. typename mpl::if_<
  1324. mpl::less_equal<precision_type, mpl::int_<53> >,
  1325. mpl::int_<53>,
  1326. typename mpl::if_<
  1327. mpl::less_equal<precision_type, mpl::int_<64> >,
  1328. mpl::int_<64>,
  1329. mpl::int_<113>
  1330. >::type
  1331. >::type
  1332. >::type tag_type;
  1333. result = igamma_temme_large(a, x, pol, static_cast<tag_type const*>(0));
  1334. if(x >= a)
  1335. invert = !invert;
  1336. if(p_derivative)
  1337. *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
  1338. break;
  1339. }
  1340. case 6:
  1341. {
  1342. // x is so small that P is necessarily very small too,
  1343. // use http://functions.wolfram.com/GammaBetaErf/GammaRegularized/06/01/05/01/01/
  1344. result = !normalised ? pow(x, a) / (a) : pow(x, a) / boost::math::tgamma(a + 1, pol);
  1345. result *= 1 - a * x / (a + 1);
  1346. if (p_derivative)
  1347. *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
  1348. break;
  1349. }
  1350. case 7:
  1351. {
  1352. // x is large,
  1353. // Compute Q:
  1354. result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
  1355. if (p_derivative)
  1356. *p_derivative = result;
  1357. result /= x;
  1358. if (result != 0)
  1359. result *= incomplete_tgamma_large_x(a, x, pol);
  1360. break;
  1361. }
  1362. }
  1363. if(normalised && (result > 1))
  1364. result = 1;
  1365. if(invert)
  1366. {
  1367. T gam = normalised ? 1 : boost::math::tgamma(a, pol);
  1368. result = gam - result;
  1369. }
  1370. if(p_derivative)
  1371. {
  1372. //
  1373. // Need to convert prefix term to derivative:
  1374. //
  1375. if((x < 1) && (tools::max_value<T>() * x < *p_derivative))
  1376. {
  1377. // overflow, just return an arbitrarily large value:
  1378. *p_derivative = tools::max_value<T>() / 2;
  1379. }
  1380. *p_derivative /= x;
  1381. }
  1382. return result;
  1383. }
  1384. //
  1385. // Ratios of two gamma functions:
  1386. //
  1387. template <class T, class Policy, class Lanczos>
  1388. T tgamma_delta_ratio_imp_lanczos(T z, T delta, const Policy& pol, const Lanczos& l)
  1389. {
  1390. BOOST_MATH_STD_USING
  1391. if(z < tools::epsilon<T>())
  1392. {
  1393. //
  1394. // We get spurious numeric overflow unless we're very careful, this
  1395. // can occur either inside Lanczos::lanczos_sum(z) or in the
  1396. // final combination of terms, to avoid this, split the product up
  1397. // into 2 (or 3) parts:
  1398. //
  1399. // G(z) / G(L) = 1 / (z * G(L)) ; z < eps, L = z + delta = delta
  1400. // z * G(L) = z * G(lim) * (G(L)/G(lim)) ; lim = largest factorial
  1401. //
  1402. if(boost::math::max_factorial<T>::value < delta)
  1403. {
  1404. T ratio = tgamma_delta_ratio_imp_lanczos(delta, T(boost::math::max_factorial<T>::value - delta), pol, l);
  1405. ratio *= z;
  1406. ratio *= boost::math::unchecked_factorial<T>(boost::math::max_factorial<T>::value - 1);
  1407. return 1 / ratio;
  1408. }
  1409. else
  1410. {
  1411. return 1 / (z * boost::math::tgamma(z + delta, pol));
  1412. }
  1413. }
  1414. T zgh = static_cast<T>(z + Lanczos::g() - constants::half<T>());
  1415. T result;
  1416. if(z + delta == z)
  1417. {
  1418. if(fabs(delta) < 10)
  1419. result = exp((constants::half<T>() - z) * boost::math::log1p(delta / zgh, pol));
  1420. else
  1421. result = 1;
  1422. }
  1423. else
  1424. {
  1425. if(fabs(delta) < 10)
  1426. {
  1427. result = exp((constants::half<T>() - z) * boost::math::log1p(delta / zgh, pol));
  1428. }
  1429. else
  1430. {
  1431. result = pow(zgh / (zgh + delta), z - constants::half<T>());
  1432. }
  1433. // Split the calculation up to avoid spurious overflow:
  1434. result *= Lanczos::lanczos_sum(z) / Lanczos::lanczos_sum(T(z + delta));
  1435. }
  1436. result *= pow(constants::e<T>() / (zgh + delta), delta);
  1437. return result;
  1438. }
  1439. //
  1440. // And again without Lanczos support this time:
  1441. //
  1442. template <class T, class Policy>
  1443. T tgamma_delta_ratio_imp_lanczos(T z, T delta, const Policy& pol, const lanczos::undefined_lanczos& l)
  1444. {
  1445. BOOST_MATH_STD_USING
  1446. //
  1447. // We adjust z and delta so that both z and z+delta are large enough for
  1448. // Sterling's approximation to hold. We can then calculate the ratio
  1449. // for the adjusted values, and rescale back down to z and z+delta.
  1450. //
  1451. // Get the required shifts first:
  1452. //
  1453. long numerator_shift = 0;
  1454. long denominator_shift = 0;
  1455. const int min_z = minimum_argument_for_bernoulli_recursion<T>();
  1456. if (min_z > z)
  1457. numerator_shift = 1 + ltrunc(min_z - z);
  1458. if (min_z > z + delta)
  1459. denominator_shift = 1 + ltrunc(min_z - z - delta);
  1460. //
  1461. // If the shifts are zero, then we can just combine scaled tgamma's
  1462. // and combine the remaining terms:
  1463. //
  1464. if (numerator_shift == 0 && denominator_shift == 0)
  1465. {
  1466. T scaled_tgamma_num = scaled_tgamma_no_lanczos(z, pol);
  1467. T scaled_tgamma_denom = scaled_tgamma_no_lanczos(T(z + delta), pol);
  1468. T result = scaled_tgamma_num / scaled_tgamma_denom;
  1469. result *= exp(z * boost::math::log1p(-delta / (z + delta), pol)) * pow((delta + z) / constants::e<T>(), -delta);
  1470. return result;
  1471. }
  1472. //
  1473. // We're going to have to rescale first, get the adjusted z and delta values,
  1474. // plus the ratio for the adjusted values:
  1475. //
  1476. T zz = z + numerator_shift;
  1477. T dd = delta - (numerator_shift - denominator_shift);
  1478. T ratio = tgamma_delta_ratio_imp_lanczos(zz, dd, pol, l);
  1479. //
  1480. // Use gamma recurrence relations to get back to the original
  1481. // z and z+delta:
  1482. //
  1483. for (long long i = 0; i < numerator_shift; ++i)
  1484. {
  1485. ratio /= (z + i);
  1486. if (i < denominator_shift)
  1487. ratio *= (z + delta + i);
  1488. }
  1489. for (long long i = numerator_shift; i < denominator_shift; ++i)
  1490. {
  1491. ratio *= (z + delta + i);
  1492. }
  1493. return ratio;
  1494. }
  1495. template <class T, class Policy>
  1496. T tgamma_delta_ratio_imp(T z, T delta, const Policy& pol)
  1497. {
  1498. BOOST_MATH_STD_USING
  1499. if((z <= 0) || (z + delta <= 0))
  1500. {
  1501. // This isn't very sofisticated, or accurate, but it does work:
  1502. return boost::math::tgamma(z, pol) / boost::math::tgamma(z + delta, pol);
  1503. }
  1504. if(floor(delta) == delta)
  1505. {
  1506. if(floor(z) == z)
  1507. {
  1508. //
  1509. // Both z and delta are integers, see if we can just use table lookup
  1510. // of the factorials to get the result:
  1511. //
  1512. if((z <= max_factorial<T>::value) && (z + delta <= max_factorial<T>::value))
  1513. {
  1514. return unchecked_factorial<T>((unsigned)itrunc(z, pol) - 1) / unchecked_factorial<T>((unsigned)itrunc(T(z + delta), pol) - 1);
  1515. }
  1516. }
  1517. if(fabs(delta) < 20)
  1518. {
  1519. //
  1520. // delta is a small integer, we can use a finite product:
  1521. //
  1522. if(delta == 0)
  1523. return 1;
  1524. if(delta < 0)
  1525. {
  1526. z -= 1;
  1527. T result = z;
  1528. while(0 != (delta += 1))
  1529. {
  1530. z -= 1;
  1531. result *= z;
  1532. }
  1533. return result;
  1534. }
  1535. else
  1536. {
  1537. T result = 1 / z;
  1538. while(0 != (delta -= 1))
  1539. {
  1540. z += 1;
  1541. result /= z;
  1542. }
  1543. return result;
  1544. }
  1545. }
  1546. }
  1547. typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
  1548. return tgamma_delta_ratio_imp_lanczos(z, delta, pol, lanczos_type());
  1549. }
  1550. template <class T, class Policy>
  1551. T tgamma_ratio_imp(T x, T y, const Policy& pol)
  1552. {
  1553. BOOST_MATH_STD_USING
  1554. if((x <= 0) || (boost::math::isinf)(x))
  1555. 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);
  1556. if((y <= 0) || (boost::math::isinf)(y))
  1557. 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);
  1558. if(x <= tools::min_value<T>())
  1559. {
  1560. // Special case for denorms...Ugh.
  1561. T shift = ldexp(T(1), tools::digits<T>());
  1562. return shift * tgamma_ratio_imp(T(x * shift), y, pol);
  1563. }
  1564. if((x < max_factorial<T>::value) && (y < max_factorial<T>::value))
  1565. {
  1566. // Rather than subtracting values, lets just call the gamma functions directly:
  1567. return boost::math::tgamma(x, pol) / boost::math::tgamma(y, pol);
  1568. }
  1569. T prefix = 1;
  1570. if(x < 1)
  1571. {
  1572. if(y < 2 * max_factorial<T>::value)
  1573. {
  1574. // We need to sidestep on x as well, otherwise we'll underflow
  1575. // before we get to factor in the prefix term:
  1576. prefix /= x;
  1577. x += 1;
  1578. while(y >= max_factorial<T>::value)
  1579. {
  1580. y -= 1;
  1581. prefix /= y;
  1582. }
  1583. return prefix * boost::math::tgamma(x, pol) / boost::math::tgamma(y, pol);
  1584. }
  1585. //
  1586. // result is almost certainly going to underflow to zero, try logs just in case:
  1587. //
  1588. return exp(boost::math::lgamma(x, pol) - boost::math::lgamma(y, pol));
  1589. }
  1590. if(y < 1)
  1591. {
  1592. if(x < 2 * max_factorial<T>::value)
  1593. {
  1594. // We need to sidestep on y as well, otherwise we'll overflow
  1595. // before we get to factor in the prefix term:
  1596. prefix *= y;
  1597. y += 1;
  1598. while(x >= max_factorial<T>::value)
  1599. {
  1600. x -= 1;
  1601. prefix *= x;
  1602. }
  1603. return prefix * boost::math::tgamma(x, pol) / boost::math::tgamma(y, pol);
  1604. }
  1605. //
  1606. // Result will almost certainly overflow, try logs just in case:
  1607. //
  1608. return exp(boost::math::lgamma(x, pol) - boost::math::lgamma(y, pol));
  1609. }
  1610. //
  1611. // Regular case, x and y both large and similar in magnitude:
  1612. //
  1613. return boost::math::tgamma_delta_ratio(x, y - x, pol);
  1614. }
  1615. template <class T, class Policy>
  1616. T gamma_p_derivative_imp(T a, T x, const Policy& pol)
  1617. {
  1618. BOOST_MATH_STD_USING
  1619. //
  1620. // Usual error checks first:
  1621. //
  1622. if(a <= 0)
  1623. 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);
  1624. if(x < 0)
  1625. 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);
  1626. //
  1627. // Now special cases:
  1628. //
  1629. if(x == 0)
  1630. {
  1631. return (a > 1) ? 0 :
  1632. (a == 1) ? 1 : policies::raise_overflow_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", 0, pol);
  1633. }
  1634. //
  1635. // Normal case:
  1636. //
  1637. typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
  1638. T f1 = detail::regularised_gamma_prefix(a, x, pol, lanczos_type());
  1639. if((x < 1) && (tools::max_value<T>() * x < f1))
  1640. {
  1641. // overflow:
  1642. return policies::raise_overflow_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", 0, pol);
  1643. }
  1644. if(f1 == 0)
  1645. {
  1646. // Underflow in calculation, use logs instead:
  1647. f1 = a * log(x) - x - lgamma(a, pol) - log(x);
  1648. f1 = exp(f1);
  1649. }
  1650. else
  1651. f1 /= x;
  1652. return f1;
  1653. }
  1654. template <class T, class Policy>
  1655. inline typename tools::promote_args<T>::type
  1656. tgamma(T z, const Policy& /* pol */, const mpl::true_)
  1657. {
  1658. BOOST_FPU_EXCEPTION_GUARD
  1659. typedef typename tools::promote_args<T>::type result_type;
  1660. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1661. typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1662. typedef typename policies::normalise<
  1663. Policy,
  1664. policies::promote_float<false>,
  1665. policies::promote_double<false>,
  1666. policies::discrete_quantile<>,
  1667. policies::assert_undefined<> >::type forwarding_policy;
  1668. 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%)");
  1669. }
  1670. template <class T, class Policy>
  1671. struct igamma_initializer
  1672. {
  1673. struct init
  1674. {
  1675. init()
  1676. {
  1677. typedef typename policies::precision<T, Policy>::type precision_type;
  1678. typedef typename mpl::if_<
  1679. mpl::or_<mpl::equal_to<precision_type, mpl::int_<0> >,
  1680. mpl::greater<precision_type, mpl::int_<113> > >,
  1681. mpl::int_<0>,
  1682. typename mpl::if_<
  1683. mpl::less_equal<precision_type, mpl::int_<53> >,
  1684. mpl::int_<53>,
  1685. typename mpl::if_<
  1686. mpl::less_equal<precision_type, mpl::int_<64> >,
  1687. mpl::int_<64>,
  1688. mpl::int_<113>
  1689. >::type
  1690. >::type
  1691. >::type tag_type;
  1692. do_init(tag_type());
  1693. }
  1694. template <int N>
  1695. static void do_init(const mpl::int_<N>&)
  1696. {
  1697. // If std::numeric_limits<T>::digits is zero, we must not call
  1698. // our inituialization code here as the precision presumably
  1699. // varies at runtime, and will not have been set yet. Plus the
  1700. // code requiring initialization isn't called when digits == 0.
  1701. if(std::numeric_limits<T>::digits)
  1702. {
  1703. boost::math::gamma_p(static_cast<T>(400), static_cast<T>(400), Policy());
  1704. }
  1705. }
  1706. static void do_init(const mpl::int_<53>&){}
  1707. void force_instantiate()const{}
  1708. };
  1709. static const init initializer;
  1710. static void force_instantiate()
  1711. {
  1712. initializer.force_instantiate();
  1713. }
  1714. };
  1715. template <class T, class Policy>
  1716. const typename igamma_initializer<T, Policy>::init igamma_initializer<T, Policy>::initializer;
  1717. template <class T, class Policy>
  1718. struct lgamma_initializer
  1719. {
  1720. struct init
  1721. {
  1722. init()
  1723. {
  1724. typedef typename policies::precision<T, Policy>::type precision_type;
  1725. typedef typename mpl::if_<
  1726. mpl::and_<
  1727. mpl::less_equal<precision_type, mpl::int_<64> >,
  1728. mpl::greater<precision_type, mpl::int_<0> >
  1729. >,
  1730. mpl::int_<64>,
  1731. typename mpl::if_<
  1732. mpl::and_<
  1733. mpl::less_equal<precision_type, mpl::int_<113> >,
  1734. mpl::greater<precision_type, mpl::int_<0> >
  1735. >,
  1736. mpl::int_<113>, mpl::int_<0> >::type
  1737. >::type tag_type;
  1738. do_init(tag_type());
  1739. }
  1740. static void do_init(const mpl::int_<64>&)
  1741. {
  1742. boost::math::lgamma(static_cast<T>(2.5), Policy());
  1743. boost::math::lgamma(static_cast<T>(1.25), Policy());
  1744. boost::math::lgamma(static_cast<T>(1.75), Policy());
  1745. }
  1746. static void do_init(const mpl::int_<113>&)
  1747. {
  1748. boost::math::lgamma(static_cast<T>(2.5), Policy());
  1749. boost::math::lgamma(static_cast<T>(1.25), Policy());
  1750. boost::math::lgamma(static_cast<T>(1.5), Policy());
  1751. boost::math::lgamma(static_cast<T>(1.75), Policy());
  1752. }
  1753. static void do_init(const mpl::int_<0>&)
  1754. {
  1755. }
  1756. void force_instantiate()const{}
  1757. };
  1758. static const init initializer;
  1759. static void force_instantiate()
  1760. {
  1761. initializer.force_instantiate();
  1762. }
  1763. };
  1764. template <class T, class Policy>
  1765. const typename lgamma_initializer<T, Policy>::init lgamma_initializer<T, Policy>::initializer;
  1766. template <class T1, class T2, class Policy>
  1767. inline typename tools::promote_args<T1, T2>::type
  1768. tgamma(T1 a, T2 z, const Policy&, const mpl::false_)
  1769. {
  1770. BOOST_FPU_EXCEPTION_GUARD
  1771. typedef typename tools::promote_args<T1, T2>::type result_type;
  1772. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1773. // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1774. typedef typename policies::normalise<
  1775. Policy,
  1776. policies::promote_float<false>,
  1777. policies::promote_double<false>,
  1778. policies::discrete_quantile<>,
  1779. policies::assert_undefined<> >::type forwarding_policy;
  1780. igamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1781. return policies::checked_narrowing_cast<result_type, forwarding_policy>(
  1782. detail::gamma_incomplete_imp(static_cast<value_type>(a),
  1783. static_cast<value_type>(z), false, true,
  1784. forwarding_policy(), static_cast<value_type*>(0)), "boost::math::tgamma<%1%>(%1%, %1%)");
  1785. }
  1786. template <class T1, class T2>
  1787. inline typename tools::promote_args<T1, T2>::type
  1788. tgamma(T1 a, T2 z, const mpl::false_ tag)
  1789. {
  1790. return tgamma(a, z, policies::policy<>(), tag);
  1791. }
  1792. } // namespace detail
  1793. template <class T>
  1794. inline typename tools::promote_args<T>::type
  1795. tgamma(T z)
  1796. {
  1797. return tgamma(z, policies::policy<>());
  1798. }
  1799. template <class T, class Policy>
  1800. inline typename tools::promote_args<T>::type
  1801. lgamma(T z, int* sign, const Policy&)
  1802. {
  1803. BOOST_FPU_EXCEPTION_GUARD
  1804. typedef typename tools::promote_args<T>::type result_type;
  1805. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1806. typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1807. typedef typename policies::normalise<
  1808. Policy,
  1809. policies::promote_float<false>,
  1810. policies::promote_double<false>,
  1811. policies::discrete_quantile<>,
  1812. policies::assert_undefined<> >::type forwarding_policy;
  1813. detail::lgamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1814. 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%)");
  1815. }
  1816. template <class T>
  1817. inline typename tools::promote_args<T>::type
  1818. lgamma(T z, int* sign)
  1819. {
  1820. return lgamma(z, sign, policies::policy<>());
  1821. }
  1822. template <class T, class Policy>
  1823. inline typename tools::promote_args<T>::type
  1824. lgamma(T x, const Policy& pol)
  1825. {
  1826. return ::boost::math::lgamma(x, 0, pol);
  1827. }
  1828. template <class T>
  1829. inline typename tools::promote_args<T>::type
  1830. lgamma(T x)
  1831. {
  1832. return ::boost::math::lgamma(x, 0, policies::policy<>());
  1833. }
  1834. template <class T, class Policy>
  1835. inline typename tools::promote_args<T>::type
  1836. tgamma1pm1(T z, const Policy& /* pol */)
  1837. {
  1838. BOOST_FPU_EXCEPTION_GUARD
  1839. typedef typename tools::promote_args<T>::type result_type;
  1840. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1841. typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1842. typedef typename policies::normalise<
  1843. Policy,
  1844. policies::promote_float<false>,
  1845. policies::promote_double<false>,
  1846. policies::discrete_quantile<>,
  1847. policies::assert_undefined<> >::type forwarding_policy;
  1848. 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%)");
  1849. }
  1850. template <class T>
  1851. inline typename tools::promote_args<T>::type
  1852. tgamma1pm1(T z)
  1853. {
  1854. return tgamma1pm1(z, policies::policy<>());
  1855. }
  1856. //
  1857. // Full upper incomplete gamma:
  1858. //
  1859. template <class T1, class T2>
  1860. inline typename tools::promote_args<T1, T2>::type
  1861. tgamma(T1 a, T2 z)
  1862. {
  1863. //
  1864. // Type T2 could be a policy object, or a value, select the
  1865. // right overload based on T2:
  1866. //
  1867. typedef typename policies::is_policy<T2>::type maybe_policy;
  1868. return detail::tgamma(a, z, maybe_policy());
  1869. }
  1870. template <class T1, class T2, class Policy>
  1871. inline typename tools::promote_args<T1, T2>::type
  1872. tgamma(T1 a, T2 z, const Policy& pol)
  1873. {
  1874. return detail::tgamma(a, z, pol, mpl::false_());
  1875. }
  1876. //
  1877. // Full lower incomplete gamma:
  1878. //
  1879. template <class T1, class T2, class Policy>
  1880. inline typename tools::promote_args<T1, T2>::type
  1881. tgamma_lower(T1 a, T2 z, const Policy&)
  1882. {
  1883. BOOST_FPU_EXCEPTION_GUARD
  1884. typedef typename tools::promote_args<T1, T2>::type result_type;
  1885. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1886. // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1887. typedef typename policies::normalise<
  1888. Policy,
  1889. policies::promote_float<false>,
  1890. policies::promote_double<false>,
  1891. policies::discrete_quantile<>,
  1892. policies::assert_undefined<> >::type forwarding_policy;
  1893. detail::igamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1894. return policies::checked_narrowing_cast<result_type, forwarding_policy>(
  1895. detail::gamma_incomplete_imp(static_cast<value_type>(a),
  1896. static_cast<value_type>(z), false, false,
  1897. forwarding_policy(), static_cast<value_type*>(0)), "tgamma_lower<%1%>(%1%, %1%)");
  1898. }
  1899. template <class T1, class T2>
  1900. inline typename tools::promote_args<T1, T2>::type
  1901. tgamma_lower(T1 a, T2 z)
  1902. {
  1903. return tgamma_lower(a, z, policies::policy<>());
  1904. }
  1905. //
  1906. // Regularised upper incomplete gamma:
  1907. //
  1908. template <class T1, class T2, class Policy>
  1909. inline typename tools::promote_args<T1, T2>::type
  1910. gamma_q(T1 a, T2 z, const Policy& /* pol */)
  1911. {
  1912. BOOST_FPU_EXCEPTION_GUARD
  1913. typedef typename tools::promote_args<T1, T2>::type result_type;
  1914. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1915. // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1916. typedef typename policies::normalise<
  1917. Policy,
  1918. policies::promote_float<false>,
  1919. policies::promote_double<false>,
  1920. policies::discrete_quantile<>,
  1921. policies::assert_undefined<> >::type forwarding_policy;
  1922. detail::igamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1923. return policies::checked_narrowing_cast<result_type, forwarding_policy>(
  1924. detail::gamma_incomplete_imp(static_cast<value_type>(a),
  1925. static_cast<value_type>(z), true, true,
  1926. forwarding_policy(), static_cast<value_type*>(0)), "gamma_q<%1%>(%1%, %1%)");
  1927. }
  1928. template <class T1, class T2>
  1929. inline typename tools::promote_args<T1, T2>::type
  1930. gamma_q(T1 a, T2 z)
  1931. {
  1932. return gamma_q(a, z, policies::policy<>());
  1933. }
  1934. //
  1935. // Regularised lower incomplete gamma:
  1936. //
  1937. template <class T1, class T2, class Policy>
  1938. inline typename tools::promote_args<T1, T2>::type
  1939. gamma_p(T1 a, T2 z, const Policy&)
  1940. {
  1941. BOOST_FPU_EXCEPTION_GUARD
  1942. typedef typename tools::promote_args<T1, T2>::type result_type;
  1943. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1944. // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1945. typedef typename policies::normalise<
  1946. Policy,
  1947. policies::promote_float<false>,
  1948. policies::promote_double<false>,
  1949. policies::discrete_quantile<>,
  1950. policies::assert_undefined<> >::type forwarding_policy;
  1951. detail::igamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1952. return policies::checked_narrowing_cast<result_type, forwarding_policy>(
  1953. detail::gamma_incomplete_imp(static_cast<value_type>(a),
  1954. static_cast<value_type>(z), true, false,
  1955. forwarding_policy(), static_cast<value_type*>(0)), "gamma_p<%1%>(%1%, %1%)");
  1956. }
  1957. template <class T1, class T2>
  1958. inline typename tools::promote_args<T1, T2>::type
  1959. gamma_p(T1 a, T2 z)
  1960. {
  1961. return gamma_p(a, z, policies::policy<>());
  1962. }
  1963. // ratios of gamma functions:
  1964. template <class T1, class T2, class Policy>
  1965. inline typename tools::promote_args<T1, T2>::type
  1966. tgamma_delta_ratio(T1 z, T2 delta, const Policy& /* pol */)
  1967. {
  1968. BOOST_FPU_EXCEPTION_GUARD
  1969. typedef typename tools::promote_args<T1, T2>::type result_type;
  1970. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1971. typedef typename policies::normalise<
  1972. Policy,
  1973. policies::promote_float<false>,
  1974. policies::promote_double<false>,
  1975. policies::discrete_quantile<>,
  1976. policies::assert_undefined<> >::type forwarding_policy;
  1977. 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%)");
  1978. }
  1979. template <class T1, class T2>
  1980. inline typename tools::promote_args<T1, T2>::type
  1981. tgamma_delta_ratio(T1 z, T2 delta)
  1982. {
  1983. return tgamma_delta_ratio(z, delta, policies::policy<>());
  1984. }
  1985. template <class T1, class T2, class Policy>
  1986. inline typename tools::promote_args<T1, T2>::type
  1987. tgamma_ratio(T1 a, T2 b, const Policy&)
  1988. {
  1989. typedef typename tools::promote_args<T1, T2>::type result_type;
  1990. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1991. typedef typename policies::normalise<
  1992. Policy,
  1993. policies::promote_float<false>,
  1994. policies::promote_double<false>,
  1995. policies::discrete_quantile<>,
  1996. policies::assert_undefined<> >::type forwarding_policy;
  1997. 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%)");
  1998. }
  1999. template <class T1, class T2>
  2000. inline typename tools::promote_args<T1, T2>::type
  2001. tgamma_ratio(T1 a, T2 b)
  2002. {
  2003. return tgamma_ratio(a, b, policies::policy<>());
  2004. }
  2005. template <class T1, class T2, class Policy>
  2006. inline typename tools::promote_args<T1, T2>::type
  2007. gamma_p_derivative(T1 a, T2 x, const Policy&)
  2008. {
  2009. BOOST_FPU_EXCEPTION_GUARD
  2010. typedef typename tools::promote_args<T1, T2>::type result_type;
  2011. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  2012. typedef typename policies::normalise<
  2013. Policy,
  2014. policies::promote_float<false>,
  2015. policies::promote_double<false>,
  2016. policies::discrete_quantile<>,
  2017. policies::assert_undefined<> >::type forwarding_policy;
  2018. 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%)");
  2019. }
  2020. template <class T1, class T2>
  2021. inline typename tools::promote_args<T1, T2>::type
  2022. gamma_p_derivative(T1 a, T2 x)
  2023. {
  2024. return gamma_p_derivative(a, x, policies::policy<>());
  2025. }
  2026. } // namespace math
  2027. } // namespace boost
  2028. #ifdef BOOST_MSVC
  2029. # pragma warning(pop)
  2030. #endif
  2031. #include <boost/math/special_functions/detail/igamma_inverse.hpp>
  2032. #include <boost/math/special_functions/detail/gamma_inva.hpp>
  2033. #include <boost/math/special_functions/erf.hpp>
  2034. #endif // BOOST_MATH_SF_GAMMA_HPP