gamma.hpp 69 KB

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