gamma.hpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  1. // Copyright John Maddock 2006-7.
  2. // Copyright Paul A. Bristow 2007.
  3. // Use, modification and distribution are subject to the
  4. // Boost Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_MATH_SF_GAMMA_HPP
  7. #define BOOST_MATH_SF_GAMMA_HPP
  8. #ifdef _MSC_VER
  9. #pragma once
  10. #endif
  11. #include <boost/config.hpp>
  12. #include <boost/math/tools/series.hpp>
  13. #include <boost/math/tools/fraction.hpp>
  14. #include <boost/math/tools/precision.hpp>
  15. #include <boost/math/tools/promotion.hpp>
  16. #include <boost/math/policies/error_handling.hpp>
  17. #include <boost/math/constants/constants.hpp>
  18. #include <boost/math/special_functions/math_fwd.hpp>
  19. #include <boost/math/special_functions/log1p.hpp>
  20. #include <boost/math/special_functions/trunc.hpp>
  21. #include <boost/math/special_functions/powm1.hpp>
  22. #include <boost/math/special_functions/sqrt1pm1.hpp>
  23. #include <boost/math/special_functions/lanczos.hpp>
  24. #include <boost/math/special_functions/fpclassify.hpp>
  25. #include <boost/math/special_functions/detail/igamma_large.hpp>
  26. #include <boost/math/special_functions/detail/unchecked_factorial.hpp>
  27. #include <boost/math/special_functions/detail/lgamma_small.hpp>
  28. #include <boost/type_traits/is_convertible.hpp>
  29. #include <boost/assert.hpp>
  30. #include <boost/mpl/greater.hpp>
  31. #include <boost/mpl/equal_to.hpp>
  32. #include <boost/mpl/greater.hpp>
  33. #include <boost/config/no_tr1/cmath.hpp>
  34. #include <algorithm>
  35. #ifdef BOOST_MSVC
  36. # pragma warning(push)
  37. # pragma warning(disable: 4702) // unreachable code (return after domain_error throw).
  38. # pragma warning(disable: 4127) // conditional expression is constant.
  39. # pragma warning(disable: 4100) // unreferenced formal parameter.
  40. // Several variables made comments,
  41. // but some difficulty as whether referenced on not may depend on macro values.
  42. // So to be safe, 4100 warnings suppressed.
  43. // TODO - revisit this?
  44. #endif
  45. namespace boost{ namespace math{
  46. namespace detail{
  47. template <class T>
  48. inline bool is_odd(T v, const boost::true_type&)
  49. {
  50. int i = static_cast<int>(v);
  51. return i&1;
  52. }
  53. template <class T>
  54. inline bool is_odd(T v, const boost::false_type&)
  55. {
  56. // Oh dear can't cast T to int!
  57. BOOST_MATH_STD_USING
  58. T modulus = v - 2 * floor(v/2);
  59. return static_cast<bool>(modulus != 0);
  60. }
  61. template <class T>
  62. inline bool is_odd(T v)
  63. {
  64. return is_odd(v, ::boost::is_convertible<T, int>());
  65. }
  66. template <class T>
  67. T sinpx(T z)
  68. {
  69. // Ad hoc function calculates x * sin(pi * x),
  70. // taking extra care near when x is near a whole number.
  71. BOOST_MATH_STD_USING
  72. int sign = 1;
  73. if(z < 0)
  74. {
  75. z = -z;
  76. }
  77. else
  78. {
  79. sign = -sign;
  80. }
  81. T fl = floor(z);
  82. T dist;
  83. if(is_odd(fl))
  84. {
  85. fl += 1;
  86. dist = fl - z;
  87. sign = -sign;
  88. }
  89. else
  90. {
  91. dist = z - fl;
  92. }
  93. BOOST_ASSERT(fl >= 0);
  94. if(dist > 0.5)
  95. dist = 1 - dist;
  96. T result = sin(dist*boost::math::constants::pi<T>());
  97. return sign*z*result;
  98. } // template <class T> T sinpx(T z)
  99. //
  100. // tgamma(z), with Lanczos support:
  101. //
  102. template <class T, class Policy, class Lanczos>
  103. T gamma_imp(T z, const Policy& pol, const Lanczos& l)
  104. {
  105. BOOST_MATH_STD_USING
  106. T result = 1;
  107. #ifdef BOOST_MATH_INSTRUMENT
  108. static bool b = false;
  109. if(!b)
  110. {
  111. std::cout << "tgamma_imp called with " << typeid(z).name() << " " << typeid(l).name() << std::endl;
  112. b = true;
  113. }
  114. #endif
  115. static const char* function = "boost::math::tgamma<%1%>(%1%)";
  116. if(z <= 0)
  117. {
  118. if(floor(z) == z)
  119. return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
  120. if(z <= -20)
  121. {
  122. result = gamma_imp(T(-z), pol, l) * sinpx(z);
  123. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  124. if((fabs(result) < 1) && (tools::max_value<T>() * fabs(result) < boost::math::constants::pi<T>()))
  125. return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
  126. result = -boost::math::constants::pi<T>() / result;
  127. if(result == 0)
  128. return policies::raise_underflow_error<T>(function, "Result of tgamma is too small to represent.", pol);
  129. if((boost::math::fpclassify)(result) == (int)FP_SUBNORMAL)
  130. return policies::raise_denorm_error<T>(function, "Result of tgamma is denormalized.", result, pol);
  131. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  132. return result;
  133. }
  134. // shift z to > 1:
  135. while(z < 0)
  136. {
  137. result /= z;
  138. z += 1;
  139. }
  140. }
  141. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  142. if((floor(z) == z) && (z < max_factorial<T>::value))
  143. {
  144. result *= unchecked_factorial<T>(itrunc(z, pol) - 1);
  145. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  146. }
  147. else
  148. {
  149. result *= Lanczos::lanczos_sum(z);
  150. T zgh = (z + static_cast<T>(Lanczos::g()) - boost::math::constants::half<T>());
  151. T lzgh = log(zgh);
  152. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  153. BOOST_MATH_INSTRUMENT_VARIABLE(tools::log_max_value<T>());
  154. if(z * lzgh > tools::log_max_value<T>())
  155. {
  156. // we're going to overflow unless this is done with care:
  157. BOOST_MATH_INSTRUMENT_VARIABLE(zgh);
  158. if(lzgh * z / 2 > tools::log_max_value<T>())
  159. return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
  160. T hp = pow(zgh, (z / 2) - T(0.25));
  161. BOOST_MATH_INSTRUMENT_VARIABLE(hp);
  162. result *= hp / exp(zgh);
  163. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  164. if(tools::max_value<T>() / hp < result)
  165. return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
  166. result *= hp;
  167. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  168. }
  169. else
  170. {
  171. BOOST_MATH_INSTRUMENT_VARIABLE(zgh);
  172. BOOST_MATH_INSTRUMENT_VARIABLE(pow(zgh, z - boost::math::constants::half<T>()));
  173. BOOST_MATH_INSTRUMENT_VARIABLE(exp(zgh));
  174. result *= pow(zgh, z - boost::math::constants::half<T>()) / exp(zgh);
  175. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  176. }
  177. }
  178. return result;
  179. }
  180. //
  181. // lgamma(z) with Lanczos support:
  182. //
  183. template <class T, class Policy, class Lanczos>
  184. T lgamma_imp(T z, const Policy& pol, const Lanczos& l, int* sign = 0)
  185. {
  186. #ifdef BOOST_MATH_INSTRUMENT
  187. static bool b = false;
  188. if(!b)
  189. {
  190. std::cout << "lgamma_imp called with " << typeid(z).name() << " " << typeid(l).name() << std::endl;
  191. b = true;
  192. }
  193. #endif
  194. BOOST_MATH_STD_USING
  195. static const char* function = "boost::math::lgamma<%1%>(%1%)";
  196. T result = 0;
  197. int sresult = 1;
  198. if(z <= 0)
  199. {
  200. // reflection formula:
  201. if(floor(z) == z)
  202. return policies::raise_pole_error<T>(function, "Evaluation of lgamma at a negative integer %1%.", z, pol);
  203. T t = sinpx(z);
  204. z = -z;
  205. if(t < 0)
  206. {
  207. t = -t;
  208. }
  209. else
  210. {
  211. sresult = -sresult;
  212. }
  213. result = log(boost::math::constants::pi<T>()) - lgamma_imp(z, pol, l) - log(t);
  214. }
  215. else if(z < 15)
  216. {
  217. typedef typename policies::precision<T, Policy>::type precision_type;
  218. typedef typename mpl::if_<
  219. mpl::and_<
  220. mpl::less_equal<precision_type, mpl::int_<64> >,
  221. mpl::greater<precision_type, mpl::int_<0> >
  222. >,
  223. mpl::int_<64>,
  224. typename mpl::if_<
  225. mpl::and_<
  226. mpl::less_equal<precision_type, mpl::int_<113> >,
  227. mpl::greater<precision_type, mpl::int_<0> >
  228. >,
  229. mpl::int_<113>, mpl::int_<0> >::type
  230. >::type tag_type;
  231. result = lgamma_small_imp<T>(z, T(z - 1), T(z - 2), tag_type(), pol, l);
  232. }
  233. else if((z >= 3) && (z < 100) && (std::numeric_limits<T>::max_exponent >= 1024))
  234. {
  235. // taking the log of tgamma reduces the error, no danger of overflow here:
  236. result = log(gamma_imp(z, pol, l));
  237. }
  238. else
  239. {
  240. // regular evaluation:
  241. T zgh = static_cast<T>(z + Lanczos::g() - boost::math::constants::half<T>());
  242. result = log(zgh) - 1;
  243. result *= z - 0.5f;
  244. result += log(Lanczos::lanczos_sum_expG_scaled(z));
  245. }
  246. if(sign)
  247. *sign = sresult;
  248. return result;
  249. }
  250. //
  251. // Incomplete gamma functions follow:
  252. //
  253. template <class T>
  254. struct upper_incomplete_gamma_fract
  255. {
  256. private:
  257. T z, a;
  258. int k;
  259. public:
  260. typedef std::pair<T,T> result_type;
  261. upper_incomplete_gamma_fract(T a1, T z1)
  262. : z(z1-a1+1), a(a1), k(0)
  263. {
  264. }
  265. result_type operator()()
  266. {
  267. ++k;
  268. z += 2;
  269. return result_type(k * (a - k), z);
  270. }
  271. };
  272. template <class T>
  273. inline T upper_gamma_fraction(T a, T z, T eps)
  274. {
  275. // Multiply result by z^a * e^-z to get the full
  276. // upper incomplete integral. Divide by tgamma(z)
  277. // to normalise.
  278. upper_incomplete_gamma_fract<T> f(a, z);
  279. return 1 / (z - a + 1 + boost::math::tools::continued_fraction_a(f, eps));
  280. }
  281. template <class T>
  282. struct lower_incomplete_gamma_series
  283. {
  284. private:
  285. T a, z, result;
  286. public:
  287. typedef T result_type;
  288. lower_incomplete_gamma_series(T a1, T z1) : a(a1), z(z1), result(1){}
  289. T operator()()
  290. {
  291. T r = result;
  292. a += 1;
  293. result *= z/a;
  294. return r;
  295. }
  296. };
  297. template <class T, class Policy>
  298. inline T lower_gamma_series(T a, T z, const Policy& pol, T init_value = 0)
  299. {
  300. // Multiply result by ((z^a) * (e^-z) / a) to get the full
  301. // lower incomplete integral. Then divide by tgamma(a)
  302. // to get the normalised value.
  303. lower_incomplete_gamma_series<T> s(a, z);
  304. boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
  305. T factor = policies::get_epsilon<T, Policy>();
  306. T result = boost::math::tools::sum_series(s, factor, max_iter, init_value);
  307. policies::check_series_iterations<T>("boost::math::detail::lower_gamma_series<%1%>(%1%)", max_iter, pol);
  308. return result;
  309. }
  310. //
  311. // Fully generic tgamma and lgamma use the incomplete partial
  312. // sums added together:
  313. //
  314. template <class T, class Policy>
  315. T gamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos& l)
  316. {
  317. static const char* function = "boost::math::tgamma<%1%>(%1%)";
  318. BOOST_MATH_STD_USING
  319. if((z <= 0) && (floor(z) == z))
  320. return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
  321. if(z <= -20)
  322. {
  323. T result = gamma_imp(T(-z), pol, l) * sinpx(z);
  324. if((fabs(result) < 1) && (tools::max_value<T>() * fabs(result) < boost::math::constants::pi<T>()))
  325. return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
  326. result = -boost::math::constants::pi<T>() / result;
  327. if(result == 0)
  328. return policies::raise_underflow_error<T>(function, "Result of tgamma is too small to represent.", pol);
  329. if((boost::math::fpclassify)(result) == (int)FP_SUBNORMAL)
  330. return policies::raise_denorm_error<T>(function, "Result of tgamma is denormalized.", result, pol);
  331. return result;
  332. }
  333. //
  334. // The upper gamma fraction is *very* slow for z < 6, actually it's very
  335. // slow to converge everywhere but recursing until z > 6 gets rid of the
  336. // worst of it's behaviour.
  337. //
  338. T prefix = 1;
  339. while(z < 6)
  340. {
  341. prefix /= z;
  342. z += 1;
  343. }
  344. BOOST_MATH_INSTRUMENT_CODE(prefix);
  345. if((floor(z) == z) && (z < max_factorial<T>::value))
  346. {
  347. prefix *= unchecked_factorial<T>(itrunc(z, pol) - 1);
  348. }
  349. else
  350. {
  351. prefix = prefix * pow(z / boost::math::constants::e<T>(), z);
  352. BOOST_MATH_INSTRUMENT_CODE(prefix);
  353. T sum = detail::lower_gamma_series(z, z, pol) / z;
  354. BOOST_MATH_INSTRUMENT_CODE(sum);
  355. sum += detail::upper_gamma_fraction(z, z, ::boost::math::policies::get_epsilon<T, Policy>());
  356. BOOST_MATH_INSTRUMENT_CODE(sum);
  357. if(fabs(tools::max_value<T>() / prefix) < fabs(sum))
  358. return policies::raise_overflow_error<T>(function, "Result of tgamma is too large to represent.", pol);
  359. BOOST_MATH_INSTRUMENT_CODE((sum * prefix));
  360. return sum * prefix;
  361. }
  362. return prefix;
  363. }
  364. template <class T, class Policy>
  365. T lgamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos& l, int*sign)
  366. {
  367. BOOST_MATH_STD_USING
  368. static const char* function = "boost::math::lgamma<%1%>(%1%)";
  369. T result = 0;
  370. int sresult = 1;
  371. if(z <= 0)
  372. {
  373. if(floor(z) == z)
  374. return policies::raise_pole_error<T>(function, "Evaluation of tgamma at a negative integer %1%.", z, pol);
  375. T t = detail::sinpx(z);
  376. z = -z;
  377. if(t < 0)
  378. {
  379. t = -t;
  380. }
  381. else
  382. {
  383. sresult = -sresult;
  384. }
  385. result = log(boost::math::constants::pi<T>()) - lgamma_imp(z, pol, l, 0) - log(t);
  386. }
  387. else if((z != 1) && (z != 2))
  388. {
  389. T limit = (std::max)(T(z+1), T(10));
  390. T prefix = z * log(limit) - limit;
  391. T sum = detail::lower_gamma_series(z, limit, pol) / z;
  392. sum += detail::upper_gamma_fraction(z, limit, ::boost::math::policies::get_epsilon<T, Policy>());
  393. result = log(sum) + prefix;
  394. }
  395. if(sign)
  396. *sign = sresult;
  397. return result;
  398. }
  399. //
  400. // This helper calculates tgamma(dz+1)-1 without cancellation errors,
  401. // used by the upper incomplete gamma with z < 1:
  402. //
  403. template <class T, class Policy, class Lanczos>
  404. T tgammap1m1_imp(T dz, Policy const& pol, const Lanczos& l)
  405. {
  406. BOOST_MATH_STD_USING
  407. typedef typename policies::precision<T,Policy>::type precision_type;
  408. typedef typename mpl::if_<
  409. mpl::or_<
  410. mpl::less_equal<precision_type, mpl::int_<0> >,
  411. mpl::greater<precision_type, mpl::int_<113> >
  412. >,
  413. typename mpl::if_<
  414. is_same<Lanczos, lanczos::lanczos24m113>,
  415. mpl::int_<113>,
  416. mpl::int_<0>
  417. >::type,
  418. typename mpl::if_<
  419. mpl::less_equal<precision_type, mpl::int_<64> >,
  420. mpl::int_<64>, mpl::int_<113> >::type
  421. >::type tag_type;
  422. T result;
  423. if(dz < 0)
  424. {
  425. if(dz < -0.5)
  426. {
  427. // Best method is simply to subtract 1 from tgamma:
  428. result = boost::math::tgamma(1+dz, pol) - 1;
  429. BOOST_MATH_INSTRUMENT_CODE(result);
  430. }
  431. else
  432. {
  433. // Use expm1 on lgamma:
  434. result = boost::math::expm1(-boost::math::log1p(dz, pol)
  435. + lgamma_small_imp<T>(dz+2, dz + 1, dz, tag_type(), pol, l));
  436. BOOST_MATH_INSTRUMENT_CODE(result);
  437. }
  438. }
  439. else
  440. {
  441. if(dz < 2)
  442. {
  443. // Use expm1 on lgamma:
  444. result = boost::math::expm1(lgamma_small_imp<T>(dz+1, dz, dz-1, tag_type(), pol, l), pol);
  445. BOOST_MATH_INSTRUMENT_CODE(result);
  446. }
  447. else
  448. {
  449. // Best method is simply to subtract 1 from tgamma:
  450. result = boost::math::tgamma(1+dz, pol) - 1;
  451. BOOST_MATH_INSTRUMENT_CODE(result);
  452. }
  453. }
  454. return result;
  455. }
  456. template <class T, class Policy>
  457. inline T tgammap1m1_imp(T dz, Policy const& pol,
  458. const ::boost::math::lanczos::undefined_lanczos& l)
  459. {
  460. BOOST_MATH_STD_USING // ADL of std names
  461. //
  462. // There should be a better solution than this, but the
  463. // algebra isn't easy for the general case....
  464. // Start by subracting 1 from tgamma:
  465. //
  466. T result = gamma_imp(T(1 + dz), pol, l) - 1;
  467. BOOST_MATH_INSTRUMENT_CODE(result);
  468. //
  469. // Test the level of cancellation error observed: we loose one bit
  470. // for each power of 2 the result is less than 1. If we would get
  471. // more bits from our most precise lgamma rational approximation,
  472. // then use that instead:
  473. //
  474. BOOST_MATH_INSTRUMENT_CODE((dz > -0.5));
  475. BOOST_MATH_INSTRUMENT_CODE((dz < 2));
  476. BOOST_MATH_INSTRUMENT_CODE((ldexp(1.0, boost::math::policies::digits<T, Policy>()) * fabs(result) < 1e34));
  477. if((dz > -0.5) && (dz < 2) && (ldexp(1.0, boost::math::policies::digits<T, Policy>()) * fabs(result) < 1e34))
  478. {
  479. result = tgammap1m1_imp(dz, pol, boost::math::lanczos::lanczos24m113());
  480. BOOST_MATH_INSTRUMENT_CODE(result);
  481. }
  482. return result;
  483. }
  484. //
  485. // Series representation for upper fraction when z is small:
  486. //
  487. template <class T>
  488. struct small_gamma2_series
  489. {
  490. typedef T result_type;
  491. small_gamma2_series(T a_, T x_) : result(-x_), x(-x_), apn(a_+1), n(1){}
  492. T operator()()
  493. {
  494. T r = result / (apn);
  495. result *= x;
  496. result /= ++n;
  497. apn += 1;
  498. return r;
  499. }
  500. private:
  501. T result, x, apn;
  502. int n;
  503. };
  504. //
  505. // calculate power term prefix (z^a)(e^-z) used in the non-normalised
  506. // incomplete gammas:
  507. //
  508. template <class T, class Policy>
  509. T full_igamma_prefix(T a, T z, const Policy& pol)
  510. {
  511. BOOST_MATH_STD_USING
  512. T prefix;
  513. T alz = a * log(z);
  514. if(z >= 1)
  515. {
  516. if((alz < tools::log_max_value<T>()) && (-z > tools::log_min_value<T>()))
  517. {
  518. prefix = pow(z, a) * exp(-z);
  519. }
  520. else if(a >= 1)
  521. {
  522. prefix = pow(z / exp(z/a), a);
  523. }
  524. else
  525. {
  526. prefix = exp(alz - z);
  527. }
  528. }
  529. else
  530. {
  531. if(alz > tools::log_min_value<T>())
  532. {
  533. prefix = pow(z, a) * exp(-z);
  534. }
  535. else if(z/a < tools::log_max_value<T>())
  536. {
  537. prefix = pow(z / exp(z/a), a);
  538. }
  539. else
  540. {
  541. prefix = exp(alz - z);
  542. }
  543. }
  544. //
  545. // This error handling isn't very good: it happens after the fact
  546. // rather than before it...
  547. //
  548. if((boost::math::fpclassify)(prefix) == (int)FP_INFINITE)
  549. 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);
  550. return prefix;
  551. }
  552. //
  553. // Compute (z^a)(e^-z)/tgamma(a)
  554. // most if the error occurs in this function:
  555. //
  556. template <class T, class Policy, class Lanczos>
  557. T regularised_gamma_prefix(T a, T z, const Policy& pol, const Lanczos& l)
  558. {
  559. BOOST_MATH_STD_USING
  560. T agh = a + static_cast<T>(Lanczos::g()) - T(0.5);
  561. T prefix;
  562. T d = ((z - a) - static_cast<T>(Lanczos::g()) + T(0.5)) / agh;
  563. if(a < 1)
  564. {
  565. //
  566. // We have to treat a < 1 as a special case because our Lanczos
  567. // approximations are optimised against the factorials with a > 1,
  568. // and for high precision types especially (128-bit reals for example)
  569. // very small values of a can give rather eroneous results for gamma
  570. // unless we do this:
  571. //
  572. // TODO: is this still required? Lanczos approx should be better now?
  573. //
  574. if(z <= tools::log_min_value<T>())
  575. {
  576. // Oh dear, have to use logs, should be free of cancellation errors though:
  577. return exp(a * log(z) - z - lgamma_imp(a, pol, l));
  578. }
  579. else
  580. {
  581. // direct calculation, no danger of overflow as gamma(a) < 1/a
  582. // for small a.
  583. return pow(z, a) * exp(-z) / gamma_imp(a, pol, l);
  584. }
  585. }
  586. else if((fabs(d*d*a) <= 100) && (a > 150))
  587. {
  588. // special case for large a and a ~ z.
  589. prefix = a * boost::math::log1pmx(d, pol) + z * static_cast<T>(0.5 - Lanczos::g()) / agh;
  590. prefix = exp(prefix);
  591. }
  592. else
  593. {
  594. //
  595. // general case.
  596. // direct computation is most accurate, but use various fallbacks
  597. // for different parts of the problem domain:
  598. //
  599. T alz = a * log(z / agh);
  600. T amz = a - z;
  601. if(((std::min)(alz, amz) <= tools::log_min_value<T>()) || ((std::max)(alz, amz) >= tools::log_max_value<T>()))
  602. {
  603. T amza = amz / a;
  604. if(((std::min)(alz, amz)/2 > tools::log_min_value<T>()) && ((std::max)(alz, amz)/2 < tools::log_max_value<T>()))
  605. {
  606. // compute square root of the result and then square it:
  607. T sq = pow(z / agh, a / 2) * exp(amz / 2);
  608. prefix = sq * sq;
  609. }
  610. else if(((std::min)(alz, amz)/4 > tools::log_min_value<T>()) && ((std::max)(alz, amz)/4 < tools::log_max_value<T>()) && (z > a))
  611. {
  612. // compute the 4th root of the result then square it twice:
  613. T sq = pow(z / agh, a / 4) * exp(amz / 4);
  614. prefix = sq * sq;
  615. prefix *= prefix;
  616. }
  617. else if((amza > tools::log_min_value<T>()) && (amza < tools::log_max_value<T>()))
  618. {
  619. prefix = pow((z * exp(amza)) / agh, a);
  620. }
  621. else
  622. {
  623. prefix = exp(alz + amz);
  624. }
  625. }
  626. else
  627. {
  628. prefix = pow(z / agh, a) * exp(amz);
  629. }
  630. }
  631. prefix *= sqrt(agh / boost::math::constants::e<T>()) / Lanczos::lanczos_sum_expG_scaled(a);
  632. return prefix;
  633. }
  634. //
  635. // And again, without Lanczos support:
  636. //
  637. template <class T, class Policy>
  638. T regularised_gamma_prefix(T a, T z, const Policy& pol, const lanczos::undefined_lanczos&)
  639. {
  640. BOOST_MATH_STD_USING
  641. T limit = (std::max)(T(10), a);
  642. T sum = detail::lower_gamma_series(a, limit, pol) / a;
  643. sum += detail::upper_gamma_fraction(a, limit, ::boost::math::policies::get_epsilon<T, Policy>());
  644. if(a < 10)
  645. {
  646. // special case for small a:
  647. T prefix = pow(z / 10, a);
  648. prefix *= exp(10-z);
  649. if(0 == prefix)
  650. {
  651. prefix = pow((z * exp((10-z)/a)) / 10, a);
  652. }
  653. prefix /= sum;
  654. return prefix;
  655. }
  656. T zoa = z / a;
  657. T amz = a - z;
  658. T alzoa = a * log(zoa);
  659. T prefix;
  660. if(((std::min)(alzoa, amz) <= tools::log_min_value<T>()) || ((std::max)(alzoa, amz) >= tools::log_max_value<T>()))
  661. {
  662. T amza = amz / a;
  663. if((amza <= tools::log_min_value<T>()) || (amza >= tools::log_max_value<T>()))
  664. {
  665. prefix = exp(alzoa + amz);
  666. }
  667. else
  668. {
  669. prefix = pow(zoa * exp(amza), a);
  670. }
  671. }
  672. else
  673. {
  674. prefix = pow(zoa, a) * exp(amz);
  675. }
  676. prefix /= sum;
  677. return prefix;
  678. }
  679. //
  680. // Upper gamma fraction for very small a:
  681. //
  682. template <class T, class Policy>
  683. inline T tgamma_small_upper_part(T a, T x, const Policy& pol, T* pgam = 0, bool invert = false, T* pderivative = 0)
  684. {
  685. BOOST_MATH_STD_USING // ADL of std functions.
  686. //
  687. // Compute the full upper fraction (Q) when a is very small:
  688. //
  689. T result;
  690. result = boost::math::tgamma1pm1(a, pol);
  691. if(pgam)
  692. *pgam = (result + 1) / a;
  693. T p = boost::math::powm1(x, a, pol);
  694. result -= p;
  695. result /= a;
  696. detail::small_gamma2_series<T> s(a, x);
  697. boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>() - 10;
  698. p += 1;
  699. if(pderivative)
  700. *pderivative = p / (*pgam * exp(x));
  701. T init_value = invert ? *pgam : 0;
  702. result = -p * tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, (init_value - result) / p);
  703. policies::check_series_iterations<T>("boost::math::tgamma_small_upper_part<%1%>(%1%, %1%)", max_iter, pol);
  704. if(invert)
  705. result = -result;
  706. return result;
  707. }
  708. //
  709. // Upper gamma fraction for integer a:
  710. //
  711. template <class T, class Policy>
  712. inline T finite_gamma_q(T a, T x, Policy const& pol, T* pderivative = 0)
  713. {
  714. //
  715. // Calculates normalised Q when a is an integer:
  716. //
  717. BOOST_MATH_STD_USING
  718. T e = exp(-x);
  719. T sum = e;
  720. if(sum != 0)
  721. {
  722. T term = sum;
  723. for(unsigned n = 1; n < a; ++n)
  724. {
  725. term /= n;
  726. term *= x;
  727. sum += term;
  728. }
  729. }
  730. if(pderivative)
  731. {
  732. *pderivative = e * pow(x, a) / boost::math::unchecked_factorial<T>(itrunc(T(a - 1), pol));
  733. }
  734. return sum;
  735. }
  736. //
  737. // Upper gamma fraction for half integer a:
  738. //
  739. template <class T, class Policy>
  740. T finite_half_gamma_q(T a, T x, T* p_derivative, const Policy& pol)
  741. {
  742. //
  743. // Calculates normalised Q when a is a half-integer:
  744. //
  745. BOOST_MATH_STD_USING
  746. T e = boost::math::erfc(sqrt(x), pol);
  747. if((e != 0) && (a > 1))
  748. {
  749. T term = exp(-x) / sqrt(constants::pi<T>() * x);
  750. term *= x;
  751. static const T half = T(1) / 2;
  752. term /= half;
  753. T sum = term;
  754. for(unsigned n = 2; n < a; ++n)
  755. {
  756. term /= n - half;
  757. term *= x;
  758. sum += term;
  759. }
  760. e += sum;
  761. if(p_derivative)
  762. {
  763. *p_derivative = 0;
  764. }
  765. }
  766. else if(p_derivative)
  767. {
  768. // We'll be dividing by x later, so calculate derivative * x:
  769. *p_derivative = sqrt(x) * exp(-x) / constants::root_pi<T>();
  770. }
  771. return e;
  772. }
  773. //
  774. // Main incomplete gamma entry point, handles all four incomplete gamma's:
  775. //
  776. template <class T, class Policy>
  777. T gamma_incomplete_imp(T a, T x, bool normalised, bool invert,
  778. const Policy& pol, T* p_derivative)
  779. {
  780. static const char* function = "boost::math::gamma_p<%1%>(%1%, %1%)";
  781. if(a <= 0)
  782. policies::raise_domain_error<T>(function, "Argument a to the incomplete gamma function must be greater than zero (got a=%1%).", a, pol);
  783. if(x < 0)
  784. policies::raise_domain_error<T>(function, "Argument x to the incomplete gamma function must be >= 0 (got x=%1%).", x, pol);
  785. BOOST_MATH_STD_USING
  786. typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
  787. T result = 0; // Just to avoid warning C4701: potentially uninitialized local variable 'result' used
  788. BOOST_ASSERT((p_derivative == 0) || (normalised == true));
  789. bool is_int, is_half_int;
  790. bool is_small_a = (a < 30) && (a <= x + 1) && (x < tools::log_max_value<T>());
  791. if(is_small_a)
  792. {
  793. T fa = floor(a);
  794. is_int = (fa == a);
  795. is_half_int = is_int ? false : (fabs(fa - a) == 0.5f);
  796. }
  797. else
  798. {
  799. is_int = is_half_int = false;
  800. }
  801. int eval_method;
  802. if(is_int && (x > 0.6))
  803. {
  804. // calculate Q via finite sum:
  805. invert = !invert;
  806. eval_method = 0;
  807. }
  808. else if(is_half_int && (x > 0.2))
  809. {
  810. // calculate Q via finite sum for half integer a:
  811. invert = !invert;
  812. eval_method = 1;
  813. }
  814. else if(x < 0.5)
  815. {
  816. //
  817. // Changeover criterion chosen to give a changeover at Q ~ 0.33
  818. //
  819. if(-0.4 / log(x) < a)
  820. {
  821. eval_method = 2;
  822. }
  823. else
  824. {
  825. eval_method = 3;
  826. }
  827. }
  828. else if(x < 1.1)
  829. {
  830. //
  831. // Changover here occurs when P ~ 0.75 or Q ~ 0.25:
  832. //
  833. if(x * 0.75f < a)
  834. {
  835. eval_method = 2;
  836. }
  837. else
  838. {
  839. eval_method = 3;
  840. }
  841. }
  842. else
  843. {
  844. //
  845. // Begin by testing whether we're in the "bad" zone
  846. // where the result will be near 0.5 and the usual
  847. // series and continued fractions are slow to converge:
  848. //
  849. bool use_temme = false;
  850. if(normalised && std::numeric_limits<T>::is_specialized && (a > 20))
  851. {
  852. T sigma = fabs((x-a)/a);
  853. if((a > 200) && (policies::digits<T, Policy>() <= 113))
  854. {
  855. //
  856. // This limit is chosen so that we use Temme's expansion
  857. // only if the result would be larger than about 10^-6.
  858. // Below that the regular series and continued fractions
  859. // converge OK, and if we use Temme's method we get increasing
  860. // errors from the dominant erfc term as it's (inexact) argument
  861. // increases in magnitude.
  862. //
  863. if(20 / a > sigma * sigma)
  864. use_temme = true;
  865. }
  866. else if(policies::digits<T, Policy>() <= 64)
  867. {
  868. // Note in this zone we can't use Temme's expansion for
  869. // types longer than an 80-bit real:
  870. // it would require too many terms in the polynomials.
  871. if(sigma < 0.4)
  872. use_temme = true;
  873. }
  874. }
  875. if(use_temme)
  876. {
  877. eval_method = 5;
  878. }
  879. else
  880. {
  881. //
  882. // Regular case where the result will not be too close to 0.5.
  883. //
  884. // Changeover here occurs at P ~ Q ~ 0.5
  885. // Note that series computation of P is about x2 faster than continued fraction
  886. // calculation of Q, so try and use the CF only when really necessary, especially
  887. // for small x.
  888. //
  889. if(x - (1 / (3 * x)) < a)
  890. {
  891. eval_method = 2;
  892. }
  893. else
  894. {
  895. eval_method = 4;
  896. invert = !invert;
  897. }
  898. }
  899. }
  900. switch(eval_method)
  901. {
  902. case 0:
  903. {
  904. result = finite_gamma_q(a, x, pol, p_derivative);
  905. if(normalised == false)
  906. result *= boost::math::tgamma(a, pol);
  907. break;
  908. }
  909. case 1:
  910. {
  911. result = finite_half_gamma_q(a, x, p_derivative, pol);
  912. if(normalised == false)
  913. result *= boost::math::tgamma(a, pol);
  914. if(p_derivative && (*p_derivative == 0))
  915. *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
  916. break;
  917. }
  918. case 2:
  919. {
  920. // Compute P:
  921. result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
  922. if(p_derivative)
  923. *p_derivative = result;
  924. if(result != 0)
  925. {
  926. T init_value = 0;
  927. if(invert)
  928. {
  929. init_value = -a * (normalised ? 1 : boost::math::tgamma(a, pol)) / result;
  930. }
  931. result *= detail::lower_gamma_series(a, x, pol, init_value) / a;
  932. if(invert)
  933. {
  934. invert = false;
  935. result = -result;
  936. }
  937. }
  938. break;
  939. }
  940. case 3:
  941. {
  942. // Compute Q:
  943. invert = !invert;
  944. T g;
  945. result = tgamma_small_upper_part(a, x, pol, &g, invert, p_derivative);
  946. invert = false;
  947. if(normalised)
  948. result /= g;
  949. break;
  950. }
  951. case 4:
  952. {
  953. // Compute Q:
  954. result = normalised ? regularised_gamma_prefix(a, x, pol, lanczos_type()) : full_igamma_prefix(a, x, pol);
  955. if(p_derivative)
  956. *p_derivative = result;
  957. if(result != 0)
  958. result *= upper_gamma_fraction(a, x, policies::get_epsilon<T, Policy>());
  959. break;
  960. }
  961. case 5:
  962. {
  963. //
  964. // Use compile time dispatch to the appropriate
  965. // Temme asymptotic expansion. This may be dead code
  966. // if T does not have numeric limits support, or has
  967. // too many digits for the most precise version of
  968. // these expansions, in that case we'll be calling
  969. // an empty function.
  970. //
  971. typedef typename policies::precision<T, Policy>::type precision_type;
  972. typedef typename mpl::if_<
  973. mpl::or_<mpl::equal_to<precision_type, mpl::int_<0> >,
  974. mpl::greater<precision_type, mpl::int_<113> > >,
  975. mpl::int_<0>,
  976. typename mpl::if_<
  977. mpl::less_equal<precision_type, mpl::int_<53> >,
  978. mpl::int_<53>,
  979. typename mpl::if_<
  980. mpl::less_equal<precision_type, mpl::int_<64> >,
  981. mpl::int_<64>,
  982. mpl::int_<113>
  983. >::type
  984. >::type
  985. >::type tag_type;
  986. result = igamma_temme_large(a, x, pol, static_cast<tag_type const*>(0));
  987. if(x >= a)
  988. invert = !invert;
  989. if(p_derivative)
  990. *p_derivative = regularised_gamma_prefix(a, x, pol, lanczos_type());
  991. break;
  992. }
  993. }
  994. if(normalised && (result > 1))
  995. result = 1;
  996. if(invert)
  997. {
  998. T gam = normalised ? 1 : boost::math::tgamma(a, pol);
  999. result = gam - result;
  1000. }
  1001. if(p_derivative)
  1002. {
  1003. //
  1004. // Need to convert prefix term to derivative:
  1005. //
  1006. if((x < 1) && (tools::max_value<T>() * x < *p_derivative))
  1007. {
  1008. // overflow, just return an arbitrarily large value:
  1009. *p_derivative = tools::max_value<T>() / 2;
  1010. }
  1011. *p_derivative /= x;
  1012. }
  1013. return result;
  1014. }
  1015. //
  1016. // Ratios of two gamma functions:
  1017. //
  1018. template <class T, class Policy, class Lanczos>
  1019. T tgamma_delta_ratio_imp_lanczos(T z, T delta, const Policy& pol, const Lanczos&)
  1020. {
  1021. BOOST_MATH_STD_USING
  1022. T zgh = z + Lanczos::g() - constants::half<T>();
  1023. T result;
  1024. if(fabs(delta) < 10)
  1025. {
  1026. result = exp((constants::half<T>() - z) * boost::math::log1p(delta / zgh, pol));
  1027. }
  1028. else
  1029. {
  1030. result = pow(zgh / (zgh + delta), z - constants::half<T>());
  1031. }
  1032. result *= pow(constants::e<T>() / (zgh + delta), delta);
  1033. result *= Lanczos::lanczos_sum(z) / Lanczos::lanczos_sum(T(z + delta));
  1034. return result;
  1035. }
  1036. //
  1037. // And again without Lanczos support this time:
  1038. //
  1039. template <class T, class Policy>
  1040. T tgamma_delta_ratio_imp_lanczos(T z, T delta, const Policy& pol, const lanczos::undefined_lanczos&)
  1041. {
  1042. BOOST_MATH_STD_USING
  1043. //
  1044. // The upper gamma fraction is *very* slow for z < 6, actually it's very
  1045. // slow to converge everywhere but recursing until z > 6 gets rid of the
  1046. // worst of it's behaviour.
  1047. //
  1048. T prefix = 1;
  1049. T zd = z + delta;
  1050. while((zd < 6) && (z < 6))
  1051. {
  1052. prefix /= z;
  1053. prefix *= zd;
  1054. z += 1;
  1055. zd += 1;
  1056. }
  1057. if(delta < 10)
  1058. {
  1059. prefix *= exp(-z * boost::math::log1p(delta / z, pol));
  1060. }
  1061. else
  1062. {
  1063. prefix *= pow(z / zd, z);
  1064. }
  1065. prefix *= pow(constants::e<T>() / zd, delta);
  1066. T sum = detail::lower_gamma_series(z, z, pol) / z;
  1067. sum += detail::upper_gamma_fraction(z, z, ::boost::math::policies::get_epsilon<T, Policy>());
  1068. T sumd = detail::lower_gamma_series(zd, zd, pol) / zd;
  1069. sumd += detail::upper_gamma_fraction(zd, zd, ::boost::math::policies::get_epsilon<T, Policy>());
  1070. sum /= sumd;
  1071. if(fabs(tools::max_value<T>() / prefix) < fabs(sum))
  1072. return policies::raise_overflow_error<T>("boost::math::tgamma_delta_ratio<%1%>(%1%, %1%)", "Result of tgamma is too large to represent.", pol);
  1073. return sum * prefix;
  1074. }
  1075. template <class T, class Policy>
  1076. T tgamma_delta_ratio_imp(T z, T delta, const Policy& pol)
  1077. {
  1078. BOOST_MATH_STD_USING
  1079. if(z <= 0)
  1080. policies::raise_domain_error<T>("boost::math::tgamma_delta_ratio<%1%>(%1%, %1%)", "Gamma function ratios only implemented for positive arguments (got a=%1%).", z, pol);
  1081. if(z+delta <= 0)
  1082. policies::raise_domain_error<T>("boost::math::tgamma_delta_ratio<%1%>(%1%, %1%)", "Gamma function ratios only implemented for positive arguments (got b=%1%).", z+delta, pol);
  1083. if(floor(delta) == delta)
  1084. {
  1085. if(floor(z) == z)
  1086. {
  1087. //
  1088. // Both z and delta are integers, see if we can just use table lookup
  1089. // of the factorials to get the result:
  1090. //
  1091. if((z <= max_factorial<T>::value) && (z + delta <= max_factorial<T>::value))
  1092. {
  1093. return unchecked_factorial<T>((unsigned)itrunc(z, pol) - 1) / unchecked_factorial<T>((unsigned)itrunc(T(z + delta), pol) - 1);
  1094. }
  1095. }
  1096. if(fabs(delta) < 20)
  1097. {
  1098. //
  1099. // delta is a small integer, we can use a finite product:
  1100. //
  1101. if(delta == 0)
  1102. return 1;
  1103. if(delta < 0)
  1104. {
  1105. z -= 1;
  1106. T result = z;
  1107. while(0 != (delta += 1))
  1108. {
  1109. z -= 1;
  1110. result *= z;
  1111. }
  1112. return result;
  1113. }
  1114. else
  1115. {
  1116. T result = 1 / z;
  1117. while(0 != (delta -= 1))
  1118. {
  1119. z += 1;
  1120. result /= z;
  1121. }
  1122. return result;
  1123. }
  1124. }
  1125. }
  1126. typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
  1127. return tgamma_delta_ratio_imp_lanczos(z, delta, pol, lanczos_type());
  1128. }
  1129. template <class T, class Policy>
  1130. T tgamma_ratio_imp(T x, T y, const Policy& pol)
  1131. {
  1132. BOOST_MATH_STD_USING
  1133. if((x <= tools::min_value<T>()) || (boost::math::isinf)(x))
  1134. 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);
  1135. if((y <= tools::min_value<T>()) || (boost::math::isinf)(y))
  1136. 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);
  1137. if((x < max_factorial<T>::value) && (y < max_factorial<T>::value))
  1138. {
  1139. // Rather than subtracting values, lets just call the gamma functions directly:
  1140. return boost::math::tgamma(x, pol) / boost::math::tgamma(y, pol);
  1141. }
  1142. T prefix = 1;
  1143. if(x < 1)
  1144. {
  1145. if(y < 2 * max_factorial<T>::value)
  1146. {
  1147. // We need to sidestep on x as well, otherwise we'll underflow
  1148. // before we get to factor in the prefix term:
  1149. prefix /= x;
  1150. x += 1;
  1151. while(y >= max_factorial<T>::value)
  1152. {
  1153. y -= 1;
  1154. prefix /= y;
  1155. }
  1156. return prefix * boost::math::tgamma(x, pol) / boost::math::tgamma(y, pol);
  1157. }
  1158. //
  1159. // result is almost certainly going to underflow to zero, try logs just in case:
  1160. //
  1161. return exp(boost::math::lgamma(x, pol) - boost::math::lgamma(y, pol));
  1162. }
  1163. if(y < 1)
  1164. {
  1165. if(x < 2 * max_factorial<T>::value)
  1166. {
  1167. // We need to sidestep on y as well, otherwise we'll overflow
  1168. // before we get to factor in the prefix term:
  1169. prefix *= y;
  1170. y += 1;
  1171. while(x >= max_factorial<T>::value)
  1172. {
  1173. x -= 1;
  1174. prefix *= x;
  1175. }
  1176. return prefix * boost::math::tgamma(x, pol) / boost::math::tgamma(y, pol);
  1177. }
  1178. //
  1179. // Result will almost certainly overflow, try logs just in case:
  1180. //
  1181. return exp(boost::math::lgamma(x, pol) - boost::math::lgamma(y, pol));
  1182. }
  1183. //
  1184. // Regular case, x and y both large and similar in magnitude:
  1185. //
  1186. return boost::math::tgamma_delta_ratio(x, y - x, pol);
  1187. }
  1188. template <class T, class Policy>
  1189. T gamma_p_derivative_imp(T a, T x, const Policy& pol)
  1190. {
  1191. //
  1192. // Usual error checks first:
  1193. //
  1194. if(a <= 0)
  1195. 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);
  1196. if(x < 0)
  1197. 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);
  1198. //
  1199. // Now special cases:
  1200. //
  1201. if(x == 0)
  1202. {
  1203. return (a > 1) ? 0 :
  1204. (a == 1) ? 1 : policies::raise_overflow_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", 0, pol);
  1205. }
  1206. //
  1207. // Normal case:
  1208. //
  1209. typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
  1210. T f1 = detail::regularised_gamma_prefix(a, x, pol, lanczos_type());
  1211. if((x < 1) && (tools::max_value<T>() * x < f1))
  1212. {
  1213. // overflow:
  1214. return policies::raise_overflow_error<T>("boost::math::gamma_p_derivative<%1%>(%1%, %1%)", 0, pol);
  1215. }
  1216. f1 /= x;
  1217. return f1;
  1218. }
  1219. template <class T, class Policy>
  1220. inline typename tools::promote_args<T>::type
  1221. tgamma(T z, const Policy& /* pol */, const mpl::true_)
  1222. {
  1223. BOOST_FPU_EXCEPTION_GUARD
  1224. typedef typename tools::promote_args<T>::type result_type;
  1225. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1226. typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1227. typedef typename policies::normalise<
  1228. Policy,
  1229. policies::promote_float<false>,
  1230. policies::promote_double<false>,
  1231. policies::discrete_quantile<>,
  1232. policies::assert_undefined<> >::type forwarding_policy;
  1233. 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%)");
  1234. }
  1235. template <class T, class Policy>
  1236. struct igamma_initializer
  1237. {
  1238. struct init
  1239. {
  1240. init()
  1241. {
  1242. typedef typename policies::precision<T, Policy>::type precision_type;
  1243. typedef typename mpl::if_<
  1244. mpl::or_<mpl::equal_to<precision_type, mpl::int_<0> >,
  1245. mpl::greater<precision_type, mpl::int_<113> > >,
  1246. mpl::int_<0>,
  1247. typename mpl::if_<
  1248. mpl::less_equal<precision_type, mpl::int_<53> >,
  1249. mpl::int_<53>,
  1250. typename mpl::if_<
  1251. mpl::less_equal<precision_type, mpl::int_<64> >,
  1252. mpl::int_<64>,
  1253. mpl::int_<113>
  1254. >::type
  1255. >::type
  1256. >::type tag_type;
  1257. do_init(tag_type());
  1258. }
  1259. template <int N>
  1260. static void do_init(const mpl::int_<N>&)
  1261. {
  1262. boost::math::gamma_p(static_cast<T>(400), static_cast<T>(400), Policy());
  1263. }
  1264. static void do_init(const mpl::int_<53>&){}
  1265. void force_instantiate()const{}
  1266. };
  1267. static const init initializer;
  1268. static void force_instantiate()
  1269. {
  1270. initializer.force_instantiate();
  1271. }
  1272. };
  1273. template <class T, class Policy>
  1274. const typename igamma_initializer<T, Policy>::init igamma_initializer<T, Policy>::initializer;
  1275. template <class T, class Policy>
  1276. struct lgamma_initializer
  1277. {
  1278. struct init
  1279. {
  1280. init()
  1281. {
  1282. typedef typename policies::precision<T, Policy>::type precision_type;
  1283. typedef typename mpl::if_<
  1284. mpl::and_<
  1285. mpl::less_equal<precision_type, mpl::int_<64> >,
  1286. mpl::greater<precision_type, mpl::int_<0> >
  1287. >,
  1288. mpl::int_<64>,
  1289. typename mpl::if_<
  1290. mpl::and_<
  1291. mpl::less_equal<precision_type, mpl::int_<113> >,
  1292. mpl::greater<precision_type, mpl::int_<0> >
  1293. >,
  1294. mpl::int_<113>, mpl::int_<0> >::type
  1295. >::type tag_type;
  1296. do_init(tag_type());
  1297. }
  1298. static void do_init(const mpl::int_<64>&)
  1299. {
  1300. boost::math::lgamma(static_cast<T>(2.5), Policy());
  1301. boost::math::lgamma(static_cast<T>(1.25), Policy());
  1302. boost::math::lgamma(static_cast<T>(1.75), Policy());
  1303. }
  1304. static void do_init(const mpl::int_<113>&)
  1305. {
  1306. boost::math::lgamma(static_cast<T>(2.5), Policy());
  1307. boost::math::lgamma(static_cast<T>(1.25), Policy());
  1308. boost::math::lgamma(static_cast<T>(1.5), Policy());
  1309. boost::math::lgamma(static_cast<T>(1.75), Policy());
  1310. }
  1311. static void do_init(const mpl::int_<0>&)
  1312. {
  1313. }
  1314. void force_instantiate()const{}
  1315. };
  1316. static const init initializer;
  1317. static void force_instantiate()
  1318. {
  1319. initializer.force_instantiate();
  1320. }
  1321. };
  1322. template <class T, class Policy>
  1323. const typename lgamma_initializer<T, Policy>::init lgamma_initializer<T, Policy>::initializer;
  1324. template <class T1, class T2, class Policy>
  1325. inline typename tools::promote_args<T1, T2>::type
  1326. tgamma(T1 a, T2 z, const Policy&, const mpl::false_)
  1327. {
  1328. BOOST_FPU_EXCEPTION_GUARD
  1329. typedef typename tools::promote_args<T1, T2>::type result_type;
  1330. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1331. // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1332. typedef typename policies::normalise<
  1333. Policy,
  1334. policies::promote_float<false>,
  1335. policies::promote_double<false>,
  1336. policies::discrete_quantile<>,
  1337. policies::assert_undefined<> >::type forwarding_policy;
  1338. igamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1339. return policies::checked_narrowing_cast<result_type, forwarding_policy>(
  1340. detail::gamma_incomplete_imp(static_cast<value_type>(a),
  1341. static_cast<value_type>(z), false, true,
  1342. forwarding_policy(), static_cast<value_type*>(0)), "boost::math::tgamma<%1%>(%1%, %1%)");
  1343. }
  1344. template <class T1, class T2>
  1345. inline typename tools::promote_args<T1, T2>::type
  1346. tgamma(T1 a, T2 z, const mpl::false_ tag)
  1347. {
  1348. return tgamma(a, z, policies::policy<>(), tag);
  1349. }
  1350. } // namespace detail
  1351. template <class T>
  1352. inline typename tools::promote_args<T>::type
  1353. tgamma(T z)
  1354. {
  1355. return tgamma(z, policies::policy<>());
  1356. }
  1357. template <class T, class Policy>
  1358. inline typename tools::promote_args<T>::type
  1359. lgamma(T z, int* sign, const Policy&)
  1360. {
  1361. BOOST_FPU_EXCEPTION_GUARD
  1362. typedef typename tools::promote_args<T>::type result_type;
  1363. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1364. typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1365. typedef typename policies::normalise<
  1366. Policy,
  1367. policies::promote_float<false>,
  1368. policies::promote_double<false>,
  1369. policies::discrete_quantile<>,
  1370. policies::assert_undefined<> >::type forwarding_policy;
  1371. detail::lgamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1372. 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%)");
  1373. }
  1374. template <class T>
  1375. inline typename tools::promote_args<T>::type
  1376. lgamma(T z, int* sign)
  1377. {
  1378. return lgamma(z, sign, policies::policy<>());
  1379. }
  1380. template <class T, class Policy>
  1381. inline typename tools::promote_args<T>::type
  1382. lgamma(T x, const Policy& pol)
  1383. {
  1384. return ::boost::math::lgamma(x, 0, pol);
  1385. }
  1386. template <class T>
  1387. inline typename tools::promote_args<T>::type
  1388. lgamma(T x)
  1389. {
  1390. return ::boost::math::lgamma(x, 0, policies::policy<>());
  1391. }
  1392. template <class T, class Policy>
  1393. inline typename tools::promote_args<T>::type
  1394. tgamma1pm1(T z, const Policy& /* pol */)
  1395. {
  1396. BOOST_FPU_EXCEPTION_GUARD
  1397. typedef typename tools::promote_args<T>::type result_type;
  1398. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1399. typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1400. typedef typename policies::normalise<
  1401. Policy,
  1402. policies::promote_float<false>,
  1403. policies::promote_double<false>,
  1404. policies::discrete_quantile<>,
  1405. policies::assert_undefined<> >::type forwarding_policy;
  1406. return policies::checked_narrowing_cast<typename remove_cv<result_type>::type, forwarding_policy>(detail::tgammap1m1_imp(static_cast<value_type>(z), forwarding_policy(), evaluation_type()), "boost::math::tgamma1pm1<%!%>(%1%)");
  1407. }
  1408. template <class T>
  1409. inline typename tools::promote_args<T>::type
  1410. tgamma1pm1(T z)
  1411. {
  1412. return tgamma1pm1(z, policies::policy<>());
  1413. }
  1414. //
  1415. // Full upper incomplete gamma:
  1416. //
  1417. template <class T1, class T2>
  1418. inline typename tools::promote_args<T1, T2>::type
  1419. tgamma(T1 a, T2 z)
  1420. {
  1421. //
  1422. // Type T2 could be a policy object, or a value, select the
  1423. // right overload based on T2:
  1424. //
  1425. typedef typename policies::is_policy<T2>::type maybe_policy;
  1426. return detail::tgamma(a, z, maybe_policy());
  1427. }
  1428. template <class T1, class T2, class Policy>
  1429. inline typename tools::promote_args<T1, T2>::type
  1430. tgamma(T1 a, T2 z, const Policy& pol)
  1431. {
  1432. return detail::tgamma(a, z, pol, mpl::false_());
  1433. }
  1434. //
  1435. // Full lower incomplete gamma:
  1436. //
  1437. template <class T1, class T2, class Policy>
  1438. inline typename tools::promote_args<T1, T2>::type
  1439. tgamma_lower(T1 a, T2 z, const Policy&)
  1440. {
  1441. BOOST_FPU_EXCEPTION_GUARD
  1442. typedef typename tools::promote_args<T1, T2>::type result_type;
  1443. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1444. // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1445. typedef typename policies::normalise<
  1446. Policy,
  1447. policies::promote_float<false>,
  1448. policies::promote_double<false>,
  1449. policies::discrete_quantile<>,
  1450. policies::assert_undefined<> >::type forwarding_policy;
  1451. detail::igamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1452. return policies::checked_narrowing_cast<result_type, forwarding_policy>(
  1453. detail::gamma_incomplete_imp(static_cast<value_type>(a),
  1454. static_cast<value_type>(z), false, false,
  1455. forwarding_policy(), static_cast<value_type*>(0)), "tgamma_lower<%1%>(%1%, %1%)");
  1456. }
  1457. template <class T1, class T2>
  1458. inline typename tools::promote_args<T1, T2>::type
  1459. tgamma_lower(T1 a, T2 z)
  1460. {
  1461. return tgamma_lower(a, z, policies::policy<>());
  1462. }
  1463. //
  1464. // Regularised upper incomplete gamma:
  1465. //
  1466. template <class T1, class T2, class Policy>
  1467. inline typename tools::promote_args<T1, T2>::type
  1468. gamma_q(T1 a, T2 z, const Policy& /* pol */)
  1469. {
  1470. BOOST_FPU_EXCEPTION_GUARD
  1471. typedef typename tools::promote_args<T1, T2>::type result_type;
  1472. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1473. // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1474. typedef typename policies::normalise<
  1475. Policy,
  1476. policies::promote_float<false>,
  1477. policies::promote_double<false>,
  1478. policies::discrete_quantile<>,
  1479. policies::assert_undefined<> >::type forwarding_policy;
  1480. detail::igamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1481. return policies::checked_narrowing_cast<result_type, forwarding_policy>(
  1482. detail::gamma_incomplete_imp(static_cast<value_type>(a),
  1483. static_cast<value_type>(z), true, true,
  1484. forwarding_policy(), static_cast<value_type*>(0)), "gamma_q<%1%>(%1%, %1%)");
  1485. }
  1486. template <class T1, class T2>
  1487. inline typename tools::promote_args<T1, T2>::type
  1488. gamma_q(T1 a, T2 z)
  1489. {
  1490. return gamma_q(a, z, policies::policy<>());
  1491. }
  1492. //
  1493. // Regularised lower incomplete gamma:
  1494. //
  1495. template <class T1, class T2, class Policy>
  1496. inline typename tools::promote_args<T1, T2>::type
  1497. gamma_p(T1 a, T2 z, const Policy&)
  1498. {
  1499. BOOST_FPU_EXCEPTION_GUARD
  1500. typedef typename tools::promote_args<T1, T2>::type result_type;
  1501. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1502. // typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
  1503. typedef typename policies::normalise<
  1504. Policy,
  1505. policies::promote_float<false>,
  1506. policies::promote_double<false>,
  1507. policies::discrete_quantile<>,
  1508. policies::assert_undefined<> >::type forwarding_policy;
  1509. detail::igamma_initializer<value_type, forwarding_policy>::force_instantiate();
  1510. return policies::checked_narrowing_cast<result_type, forwarding_policy>(
  1511. detail::gamma_incomplete_imp(static_cast<value_type>(a),
  1512. static_cast<value_type>(z), true, false,
  1513. forwarding_policy(), static_cast<value_type*>(0)), "gamma_p<%1%>(%1%, %1%)");
  1514. }
  1515. template <class T1, class T2>
  1516. inline typename tools::promote_args<T1, T2>::type
  1517. gamma_p(T1 a, T2 z)
  1518. {
  1519. return gamma_p(a, z, policies::policy<>());
  1520. }
  1521. // ratios of gamma functions:
  1522. template <class T1, class T2, class Policy>
  1523. inline typename tools::promote_args<T1, T2>::type
  1524. tgamma_delta_ratio(T1 z, T2 delta, const Policy& /* pol */)
  1525. {
  1526. BOOST_FPU_EXCEPTION_GUARD
  1527. typedef typename tools::promote_args<T1, T2>::type result_type;
  1528. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1529. typedef typename policies::normalise<
  1530. Policy,
  1531. policies::promote_float<false>,
  1532. policies::promote_double<false>,
  1533. policies::discrete_quantile<>,
  1534. policies::assert_undefined<> >::type forwarding_policy;
  1535. 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%)");
  1536. }
  1537. template <class T1, class T2>
  1538. inline typename tools::promote_args<T1, T2>::type
  1539. tgamma_delta_ratio(T1 z, T2 delta)
  1540. {
  1541. return tgamma_delta_ratio(z, delta, policies::policy<>());
  1542. }
  1543. template <class T1, class T2, class Policy>
  1544. inline typename tools::promote_args<T1, T2>::type
  1545. tgamma_ratio(T1 a, T2 b, const Policy&)
  1546. {
  1547. typedef typename tools::promote_args<T1, T2>::type result_type;
  1548. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1549. typedef typename policies::normalise<
  1550. Policy,
  1551. policies::promote_float<false>,
  1552. policies::promote_double<false>,
  1553. policies::discrete_quantile<>,
  1554. policies::assert_undefined<> >::type forwarding_policy;
  1555. 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%)");
  1556. }
  1557. template <class T1, class T2>
  1558. inline typename tools::promote_args<T1, T2>::type
  1559. tgamma_ratio(T1 a, T2 b)
  1560. {
  1561. return tgamma_ratio(a, b, policies::policy<>());
  1562. }
  1563. template <class T1, class T2, class Policy>
  1564. inline typename tools::promote_args<T1, T2>::type
  1565. gamma_p_derivative(T1 a, T2 x, const Policy&)
  1566. {
  1567. BOOST_FPU_EXCEPTION_GUARD
  1568. typedef typename tools::promote_args<T1, T2>::type result_type;
  1569. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  1570. typedef typename policies::normalise<
  1571. Policy,
  1572. policies::promote_float<false>,
  1573. policies::promote_double<false>,
  1574. policies::discrete_quantile<>,
  1575. policies::assert_undefined<> >::type forwarding_policy;
  1576. 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%)");
  1577. }
  1578. template <class T1, class T2>
  1579. inline typename tools::promote_args<T1, T2>::type
  1580. gamma_p_derivative(T1 a, T2 x)
  1581. {
  1582. return gamma_p_derivative(a, x, policies::policy<>());
  1583. }
  1584. } // namespace math
  1585. } // namespace boost
  1586. #ifdef BOOST_MSVC
  1587. # pragma warning(pop)
  1588. #endif
  1589. #include <boost/math/special_functions/detail/igamma_inverse.hpp>
  1590. #include <boost/math/special_functions/detail/gamma_inva.hpp>
  1591. #include <boost/math/special_functions/erf.hpp>
  1592. #endif // BOOST_MATH_SF_GAMMA_HPP