gamma.hpp 80 KB

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