negative_binomial.hpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. // boost\math\special_functions\negative_binomial.hpp
  2. // Copyright Paul A. Bristow 2007.
  3. // Copyright John Maddock 2007.
  4. // Use, modification and distribution are subject to the
  5. // Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt
  7. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  8. // http://en.wikipedia.org/wiki/negative_binomial_distribution
  9. // http://mathworld.wolfram.com/NegativeBinomialDistribution.html
  10. // http://documents.wolfram.com/teachersedition/Teacher/Statistics/DiscreteDistributions.html
  11. // The negative binomial distribution NegativeBinomialDistribution[n, p]
  12. // is the distribution of the number (k) of failures that occur in a sequence of trials before
  13. // r successes have occurred, where the probability of success in each trial is p.
  14. // In a sequence of Bernoulli trials or events
  15. // (independent, yes or no, succeed or fail) with success_fraction probability p,
  16. // negative_binomial is the probability that k or fewer failures
  17. // preceed the r th trial's success.
  18. // random variable k is the number of failures (NOT the probability).
  19. // Negative_binomial distribution is a discrete probability distribution.
  20. // But note that the negative binomial distribution
  21. // (like others including the binomial, Poisson & Bernoulli)
  22. // is strictly defined as a discrete function: only integral values of k are envisaged.
  23. // However because of the method of calculation using a continuous gamma function,
  24. // it is convenient to treat it as if a continous function,
  25. // and permit non-integral values of k.
  26. // However, by default the policy is to use discrete_quantile_policy.
  27. // To enforce the strict mathematical model, users should use conversion
  28. // on k outside this function to ensure that k is integral.
  29. // MATHCAD cumulative negative binomial pnbinom(k, n, p)
  30. // Implementation note: much greater speed, and perhaps greater accuracy,
  31. // might be achieved for extreme values by using a normal approximation.
  32. // This is NOT been tested or implemented.
  33. #ifndef BOOST_MATH_SPECIAL_NEGATIVE_BINOMIAL_HPP
  34. #define BOOST_MATH_SPECIAL_NEGATIVE_BINOMIAL_HPP
  35. #include <boost/math/distributions/fwd.hpp>
  36. #include <boost/math/special_functions/beta.hpp> // for ibeta(a, b, x) == Ix(a, b).
  37. #include <boost/math/distributions/complement.hpp> // complement.
  38. #include <boost/math/distributions/detail/common_error_handling.hpp> // error checks domain_error & logic_error.
  39. #include <boost/math/special_functions/fpclassify.hpp> // isnan.
  40. #include <boost/math/tools/roots.hpp> // for root finding.
  41. #include <boost/math/distributions/detail/inv_discrete_quantile.hpp>
  42. #include <boost/type_traits/is_floating_point.hpp>
  43. #include <boost/type_traits/is_integral.hpp>
  44. #include <boost/type_traits/is_same.hpp>
  45. #include <boost/mpl/if.hpp>
  46. #include <limits> // using std::numeric_limits;
  47. #include <utility>
  48. #if defined (BOOST_MSVC)
  49. # pragma warning(push)
  50. // This believed not now necessary, so commented out.
  51. //# pragma warning(disable: 4702) // unreachable code.
  52. // in domain_error_imp in error_handling.
  53. #endif
  54. namespace boost
  55. {
  56. namespace math
  57. {
  58. namespace negative_binomial_detail
  59. {
  60. // Common error checking routines for negative binomial distribution functions:
  61. template <class RealType, class Policy>
  62. inline bool check_successes(const char* function, const RealType& r, RealType* result, const Policy& pol)
  63. {
  64. if( !(boost::math::isfinite)(r) || (r <= 0) )
  65. {
  66. *result = policies::raise_domain_error<RealType>(
  67. function,
  68. "Number of successes argument is %1%, but must be > 0 !", r, pol);
  69. return false;
  70. }
  71. return true;
  72. }
  73. template <class RealType, class Policy>
  74. inline bool check_success_fraction(const char* function, const RealType& p, RealType* result, const Policy& pol)
  75. {
  76. if( !(boost::math::isfinite)(p) || (p < 0) || (p > 1) )
  77. {
  78. *result = policies::raise_domain_error<RealType>(
  79. function,
  80. "Success fraction argument is %1%, but must be >= 0 and <= 1 !", p, pol);
  81. return false;
  82. }
  83. return true;
  84. }
  85. template <class RealType, class Policy>
  86. inline bool check_dist(const char* function, const RealType& r, const RealType& p, RealType* result, const Policy& pol)
  87. {
  88. return check_success_fraction(function, p, result, pol)
  89. && check_successes(function, r, result, pol);
  90. }
  91. template <class RealType, class Policy>
  92. inline bool check_dist_and_k(const char* function, const RealType& r, const RealType& p, RealType k, RealType* result, const Policy& pol)
  93. {
  94. if(check_dist(function, r, p, result, pol) == false)
  95. {
  96. return false;
  97. }
  98. if( !(boost::math::isfinite)(k) || (k < 0) )
  99. { // Check k failures.
  100. *result = policies::raise_domain_error<RealType>(
  101. function,
  102. "Number of failures argument is %1%, but must be >= 0 !", k, pol);
  103. return false;
  104. }
  105. return true;
  106. } // Check_dist_and_k
  107. template <class RealType, class Policy>
  108. inline bool check_dist_and_prob(const char* function, const RealType& r, RealType p, RealType prob, RealType* result, const Policy& pol)
  109. {
  110. if((check_dist(function, r, p, result, pol) && detail::check_probability(function, prob, result, pol)) == false)
  111. {
  112. return false;
  113. }
  114. return true;
  115. } // check_dist_and_prob
  116. } // namespace negative_binomial_detail
  117. template <class RealType = double, class Policy = policies::policy<> >
  118. class negative_binomial_distribution
  119. {
  120. public:
  121. typedef RealType value_type;
  122. typedef Policy policy_type;
  123. negative_binomial_distribution(RealType r, RealType p) : m_r(r), m_p(p)
  124. { // Constructor.
  125. RealType result;
  126. negative_binomial_detail::check_dist(
  127. "negative_binomial_distribution<%1%>::negative_binomial_distribution",
  128. m_r, // Check successes r > 0.
  129. m_p, // Check success_fraction 0 <= p <= 1.
  130. &result, Policy());
  131. } // negative_binomial_distribution constructor.
  132. // Private data getter class member functions.
  133. RealType success_fraction() const
  134. { // Probability of success as fraction in range 0 to 1.
  135. return m_p;
  136. }
  137. RealType successes() const
  138. { // Total number of successes r.
  139. return m_r;
  140. }
  141. static RealType find_lower_bound_on_p(
  142. RealType trials,
  143. RealType successes,
  144. RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.
  145. {
  146. static const char* function = "boost::math::negative_binomial<%1%>::find_lower_bound_on_p";
  147. RealType result = 0; // of error checks.
  148. RealType failures = trials - successes;
  149. if(false == detail::check_probability(function, alpha, &result, Policy())
  150. && negative_binomial_detail::check_dist_and_k(
  151. function, successes, RealType(0), failures, &result, Policy()))
  152. {
  153. return result;
  154. }
  155. // Use complement ibeta_inv function for lower bound.
  156. // This is adapted from the corresponding binomial formula
  157. // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
  158. // This is a Clopper-Pearson interval, and may be overly conservative,
  159. // see also "A Simple Improved Inferential Method for Some
  160. // Discrete Distributions" Yong CAI and K. KRISHNAMOORTHY
  161. // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf
  162. //
  163. return ibeta_inv(successes, failures + 1, alpha, static_cast<RealType*>(0), Policy());
  164. } // find_lower_bound_on_p
  165. static RealType find_upper_bound_on_p(
  166. RealType trials,
  167. RealType successes,
  168. RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.
  169. {
  170. static const char* function = "boost::math::negative_binomial<%1%>::find_upper_bound_on_p";
  171. RealType result = 0; // of error checks.
  172. RealType failures = trials - successes;
  173. if(false == negative_binomial_detail::check_dist_and_k(
  174. function, successes, RealType(0), failures, &result, Policy())
  175. && detail::check_probability(function, alpha, &result, Policy()))
  176. {
  177. return result;
  178. }
  179. if(failures == 0)
  180. return 1;
  181. // Use complement ibetac_inv function for upper bound.
  182. // Note adjusted failures value: *not* failures+1 as usual.
  183. // This is adapted from the corresponding binomial formula
  184. // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
  185. // This is a Clopper-Pearson interval, and may be overly conservative,
  186. // see also "A Simple Improved Inferential Method for Some
  187. // Discrete Distributions" Yong CAI and K. KRISHNAMOORTHY
  188. // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf
  189. //
  190. return ibetac_inv(successes, failures, alpha, static_cast<RealType*>(0), Policy());
  191. } // find_upper_bound_on_p
  192. // Estimate number of trials :
  193. // "How many trials do I need to be P% sure of seeing k or fewer failures?"
  194. static RealType find_minimum_number_of_trials(
  195. RealType k, // number of failures (k >= 0).
  196. RealType p, // success fraction 0 <= p <= 1.
  197. RealType alpha) // risk level threshold 0 <= alpha <= 1.
  198. {
  199. static const char* function = "boost::math::negative_binomial<%1%>::find_minimum_number_of_trials";
  200. // Error checks:
  201. RealType result = 0;
  202. if(false == negative_binomial_detail::check_dist_and_k(
  203. function, RealType(1), p, k, &result, Policy())
  204. && detail::check_probability(function, alpha, &result, Policy()))
  205. { return result; }
  206. result = ibeta_inva(k + 1, p, alpha, Policy()); // returns n - k
  207. return result + k;
  208. } // RealType find_number_of_failures
  209. static RealType find_maximum_number_of_trials(
  210. RealType k, // number of failures (k >= 0).
  211. RealType p, // success fraction 0 <= p <= 1.
  212. RealType alpha) // risk level threshold 0 <= alpha <= 1.
  213. {
  214. static const char* function = "boost::math::negative_binomial<%1%>::find_maximum_number_of_trials";
  215. // Error checks:
  216. RealType result = 0;
  217. if(false == negative_binomial_detail::check_dist_and_k(
  218. function, RealType(1), p, k, &result, Policy())
  219. && detail::check_probability(function, alpha, &result, Policy()))
  220. { return result; }
  221. result = ibetac_inva(k + 1, p, alpha, Policy()); // returns n - k
  222. return result + k;
  223. } // RealType find_number_of_trials complemented
  224. private:
  225. RealType m_r; // successes.
  226. RealType m_p; // success_fraction
  227. }; // template <class RealType, class Policy> class negative_binomial_distribution
  228. typedef negative_binomial_distribution<double> negative_binomial; // Reserved name of type double.
  229. template <class RealType, class Policy>
  230. inline const std::pair<RealType, RealType> range(const negative_binomial_distribution<RealType, Policy>& /* dist */)
  231. { // Range of permissible values for random variable k.
  232. using boost::math::tools::max_value;
  233. return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // max_integer?
  234. }
  235. template <class RealType, class Policy>
  236. inline const std::pair<RealType, RealType> support(const negative_binomial_distribution<RealType, Policy>& /* dist */)
  237. { // Range of supported values for random variable k.
  238. // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
  239. using boost::math::tools::max_value;
  240. return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // max_integer?
  241. }
  242. template <class RealType, class Policy>
  243. inline RealType mean(const negative_binomial_distribution<RealType, Policy>& dist)
  244. { // Mean of Negative Binomial distribution = r(1-p)/p.
  245. return dist.successes() * (1 - dist.success_fraction() ) / dist.success_fraction();
  246. } // mean
  247. //template <class RealType, class Policy>
  248. //inline RealType median(const negative_binomial_distribution<RealType, Policy>& dist)
  249. //{ // Median of negative_binomial_distribution is not defined.
  250. // return policies::raise_domain_error<RealType>(BOOST_CURRENT_FUNCTION, "Median is not implemented, result is %1%!", std::numeric_limits<RealType>::quiet_NaN());
  251. //} // median
  252. // Now implemented via quantile(half) in derived accessors.
  253. template <class RealType, class Policy>
  254. inline RealType mode(const negative_binomial_distribution<RealType, Policy>& dist)
  255. { // Mode of Negative Binomial distribution = floor[(r-1) * (1 - p)/p]
  256. BOOST_MATH_STD_USING // ADL of std functions.
  257. return floor((dist.successes() -1) * (1 - dist.success_fraction()) / dist.success_fraction());
  258. } // mode
  259. template <class RealType, class Policy>
  260. inline RealType skewness(const negative_binomial_distribution<RealType, Policy>& dist)
  261. { // skewness of Negative Binomial distribution = 2-p / (sqrt(r(1-p))
  262. BOOST_MATH_STD_USING // ADL of std functions.
  263. RealType p = dist.success_fraction();
  264. RealType r = dist.successes();
  265. return (2 - p) /
  266. sqrt(r * (1 - p));
  267. } // skewness
  268. template <class RealType, class Policy>
  269. inline RealType kurtosis(const negative_binomial_distribution<RealType, Policy>& dist)
  270. { // kurtosis of Negative Binomial distribution
  271. // http://en.wikipedia.org/wiki/Negative_binomial is kurtosis_excess so add 3
  272. RealType p = dist.success_fraction();
  273. RealType r = dist.successes();
  274. return 3 + (6 / r) + ((p * p) / (r * (1 - p)));
  275. } // kurtosis
  276. template <class RealType, class Policy>
  277. inline RealType kurtosis_excess(const negative_binomial_distribution<RealType, Policy>& dist)
  278. { // kurtosis excess of Negative Binomial distribution
  279. // http://mathworld.wolfram.com/Kurtosis.html table of kurtosis_excess
  280. RealType p = dist.success_fraction();
  281. RealType r = dist.successes();
  282. return (6 - p * (6-p)) / (r * (1-p));
  283. } // kurtosis_excess
  284. template <class RealType, class Policy>
  285. inline RealType variance(const negative_binomial_distribution<RealType, Policy>& dist)
  286. { // Variance of Binomial distribution = r (1-p) / p^2.
  287. return dist.successes() * (1 - dist.success_fraction())
  288. / (dist.success_fraction() * dist.success_fraction());
  289. } // variance
  290. // RealType standard_deviation(const negative_binomial_distribution<RealType, Policy>& dist)
  291. // standard_deviation provided by derived accessors.
  292. // RealType hazard(const negative_binomial_distribution<RealType, Policy>& dist)
  293. // hazard of Negative Binomial distribution provided by derived accessors.
  294. // RealType chf(const negative_binomial_distribution<RealType, Policy>& dist)
  295. // chf of Negative Binomial distribution provided by derived accessors.
  296. template <class RealType, class Policy>
  297. inline RealType pdf(const negative_binomial_distribution<RealType, Policy>& dist, const RealType& k)
  298. { // Probability Density/Mass Function.
  299. BOOST_FPU_EXCEPTION_GUARD
  300. static const char* function = "boost::math::pdf(const negative_binomial_distribution<%1%>&, %1%)";
  301. RealType r = dist.successes();
  302. RealType p = dist.success_fraction();
  303. RealType result = 0;
  304. if(false == negative_binomial_detail::check_dist_and_k(
  305. function,
  306. r,
  307. dist.success_fraction(),
  308. k,
  309. &result, Policy()))
  310. {
  311. return result;
  312. }
  313. result = (p/(r + k)) * ibeta_derivative(r, static_cast<RealType>(k+1), p, Policy());
  314. // Equivalent to:
  315. // return exp(lgamma(r + k) - lgamma(r) - lgamma(k+1)) * pow(p, r) * pow((1-p), k);
  316. return result;
  317. } // negative_binomial_pdf
  318. template <class RealType, class Policy>
  319. inline RealType cdf(const negative_binomial_distribution<RealType, Policy>& dist, const RealType& k)
  320. { // Cumulative Distribution Function of Negative Binomial.
  321. static const char* function = "boost::math::cdf(const negative_binomial_distribution<%1%>&, %1%)";
  322. using boost::math::ibeta; // Regularized incomplete beta function.
  323. // k argument may be integral, signed, or unsigned, or floating point.
  324. // If necessary, it has already been promoted from an integral type.
  325. RealType p = dist.success_fraction();
  326. RealType r = dist.successes();
  327. // Error check:
  328. RealType result = 0;
  329. if(false == negative_binomial_detail::check_dist_and_k(
  330. function,
  331. r,
  332. dist.success_fraction(),
  333. k,
  334. &result, Policy()))
  335. {
  336. return result;
  337. }
  338. RealType probability = ibeta(r, static_cast<RealType>(k+1), p, Policy());
  339. // Ip(r, k+1) = ibeta(r, k+1, p)
  340. return probability;
  341. } // cdf Cumulative Distribution Function Negative Binomial.
  342. template <class RealType, class Policy>
  343. inline RealType cdf(const complemented2_type<negative_binomial_distribution<RealType, Policy>, RealType>& c)
  344. { // Complemented Cumulative Distribution Function Negative Binomial.
  345. static const char* function = "boost::math::cdf(const negative_binomial_distribution<%1%>&, %1%)";
  346. using boost::math::ibetac; // Regularized incomplete beta function complement.
  347. // k argument may be integral, signed, or unsigned, or floating point.
  348. // If necessary, it has already been promoted from an integral type.
  349. RealType const& k = c.param;
  350. negative_binomial_distribution<RealType, Policy> const& dist = c.dist;
  351. RealType p = dist.success_fraction();
  352. RealType r = dist.successes();
  353. // Error check:
  354. RealType result = 0;
  355. if(false == negative_binomial_detail::check_dist_and_k(
  356. function,
  357. r,
  358. p,
  359. k,
  360. &result, Policy()))
  361. {
  362. return result;
  363. }
  364. // Calculate cdf negative binomial using the incomplete beta function.
  365. // Use of ibeta here prevents cancellation errors in calculating
  366. // 1-p if p is very small, perhaps smaller than machine epsilon.
  367. // Ip(k+1, r) = ibetac(r, k+1, p)
  368. // constrain_probability here?
  369. RealType probability = ibetac(r, static_cast<RealType>(k+1), p, Policy());
  370. // Numerical errors might cause probability to be slightly outside the range < 0 or > 1.
  371. // This might cause trouble downstream, so warn, possibly throw exception, but constrain to the limits.
  372. return probability;
  373. } // cdf Cumulative Distribution Function Negative Binomial.
  374. template <class RealType, class Policy>
  375. inline RealType quantile(const negative_binomial_distribution<RealType, Policy>& dist, const RealType& P)
  376. { // Quantile, percentile/100 or Percent Point Negative Binomial function.
  377. // Return the number of expected failures k for a given probability p.
  378. // Inverse cumulative Distribution Function or Quantile (percentile / 100) of negative_binomial Probability.
  379. // MAthCAD pnbinom return smallest k such that negative_binomial(k, n, p) >= probability.
  380. // k argument may be integral, signed, or unsigned, or floating point.
  381. // BUT Cephes/CodeCogs says: finds argument p (0 to 1) such that cdf(k, n, p) = y
  382. static const char* function = "boost::math::quantile(const negative_binomial_distribution<%1%>&, %1%)";
  383. BOOST_MATH_STD_USING // ADL of std functions.
  384. RealType p = dist.success_fraction();
  385. RealType r = dist.successes();
  386. // Check dist and P.
  387. RealType result = 0;
  388. if(false == negative_binomial_detail::check_dist_and_prob
  389. (function, r, p, P, &result, Policy()))
  390. {
  391. return result;
  392. }
  393. // Special cases.
  394. if (P == 1)
  395. { // Would need +infinity failures for total confidence.
  396. result = policies::raise_overflow_error<RealType>(
  397. function,
  398. "Probability argument is 1, which implies infinite failures !", Policy());
  399. return result;
  400. // usually means return +std::numeric_limits<RealType>::infinity();
  401. // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR
  402. }
  403. if (P == 0)
  404. { // No failures are expected if P = 0.
  405. return 0; // Total trials will be just dist.successes.
  406. }
  407. if (P <= pow(dist.success_fraction(), dist.successes()))
  408. { // p <= pdf(dist, 0) == cdf(dist, 0)
  409. return 0;
  410. }
  411. if(p == 0)
  412. { // Would need +infinity failures for total confidence.
  413. result = policies::raise_overflow_error<RealType>(
  414. function,
  415. "Success fraction is 0, which implies infinite failures !", Policy());
  416. return result;
  417. // usually means return +std::numeric_limits<RealType>::infinity();
  418. // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR
  419. }
  420. /*
  421. // Calculate quantile of negative_binomial using the inverse incomplete beta function.
  422. using boost::math::ibeta_invb;
  423. return ibeta_invb(r, p, P, Policy()) - 1; //
  424. */
  425. RealType guess = 0;
  426. RealType factor = 5;
  427. if(r * r * r * P * p > 0.005)
  428. guess = detail::inverse_negative_binomial_cornish_fisher(r, p, RealType(1-p), P, RealType(1-P), Policy());
  429. if(guess < 10)
  430. {
  431. //
  432. // Cornish-Fisher Negative binomial approximation not accurate in this area:
  433. //
  434. guess = (std::min)(RealType(r * 2), RealType(10));
  435. }
  436. else
  437. factor = (1-P < sqrt(tools::epsilon<RealType>())) ? 2 : (guess < 20 ? 1.2f : 1.1f);
  438. BOOST_MATH_INSTRUMENT_CODE("guess = " << guess);
  439. //
  440. // Max iterations permitted:
  441. //
  442. boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
  443. typedef typename Policy::discrete_quantile_type discrete_type;
  444. return detail::inverse_discrete_quantile(
  445. dist,
  446. P,
  447. false,
  448. guess,
  449. factor,
  450. RealType(1),
  451. discrete_type(),
  452. max_iter);
  453. } // RealType quantile(const negative_binomial_distribution dist, p)
  454. template <class RealType, class Policy>
  455. inline RealType quantile(const complemented2_type<negative_binomial_distribution<RealType, Policy>, RealType>& c)
  456. { // Quantile or Percent Point Binomial function.
  457. // Return the number of expected failures k for a given
  458. // complement of the probability Q = 1 - P.
  459. static const char* function = "boost::math::quantile(const negative_binomial_distribution<%1%>&, %1%)";
  460. BOOST_MATH_STD_USING
  461. // Error checks:
  462. RealType Q = c.param;
  463. const negative_binomial_distribution<RealType, Policy>& dist = c.dist;
  464. RealType p = dist.success_fraction();
  465. RealType r = dist.successes();
  466. RealType result = 0;
  467. if(false == negative_binomial_detail::check_dist_and_prob(
  468. function,
  469. r,
  470. p,
  471. Q,
  472. &result, Policy()))
  473. {
  474. return result;
  475. }
  476. // Special cases:
  477. //
  478. if(Q == 1)
  479. { // There may actually be no answer to this question,
  480. // since the probability of zero failures may be non-zero,
  481. return 0; // but zero is the best we can do:
  482. }
  483. if(Q == 0)
  484. { // Probability 1 - Q == 1 so infinite failures to achieve certainty.
  485. // Would need +infinity failures for total confidence.
  486. result = policies::raise_overflow_error<RealType>(
  487. function,
  488. "Probability argument complement is 0, which implies infinite failures !", Policy());
  489. return result;
  490. // usually means return +std::numeric_limits<RealType>::infinity();
  491. // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR
  492. }
  493. if (-Q <= boost::math::powm1(dist.success_fraction(), dist.successes(), Policy()))
  494. { // q <= cdf(complement(dist, 0)) == pdf(dist, 0)
  495. return 0; //
  496. }
  497. if(p == 0)
  498. { // Success fraction is 0 so infinite failures to achieve certainty.
  499. // Would need +infinity failures for total confidence.
  500. result = policies::raise_overflow_error<RealType>(
  501. function,
  502. "Success fraction is 0, which implies infinite failures !", Policy());
  503. return result;
  504. // usually means return +std::numeric_limits<RealType>::infinity();
  505. // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR
  506. }
  507. //return ibetac_invb(r, p, Q, Policy()) -1;
  508. RealType guess = 0;
  509. RealType factor = 5;
  510. if(r * r * r * (1-Q) * p > 0.005)
  511. guess = detail::inverse_negative_binomial_cornish_fisher(r, p, RealType(1-p), RealType(1-Q), Q, Policy());
  512. if(guess < 10)
  513. {
  514. //
  515. // Cornish-Fisher Negative binomial approximation not accurate in this area:
  516. //
  517. guess = (std::min)(RealType(r * 2), RealType(10));
  518. }
  519. else
  520. factor = (Q < sqrt(tools::epsilon<RealType>())) ? 2 : (guess < 20 ? 1.2f : 1.1f);
  521. BOOST_MATH_INSTRUMENT_CODE("guess = " << guess);
  522. //
  523. // Max iterations permitted:
  524. //
  525. boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
  526. typedef typename Policy::discrete_quantile_type discrete_type;
  527. return detail::inverse_discrete_quantile(
  528. dist,
  529. Q,
  530. true,
  531. guess,
  532. factor,
  533. RealType(1),
  534. discrete_type(),
  535. max_iter);
  536. } // quantile complement
  537. } // namespace math
  538. } // namespace boost
  539. // This include must be at the end, *after* the accessors
  540. // for this distribution have been defined, in order to
  541. // keep compilers that support two-phase lookup happy.
  542. #include <boost/math/distributions/detail/derived_accessors.hpp>
  543. #if defined (BOOST_MSVC)
  544. # pragma warning(pop)
  545. #endif
  546. #endif // BOOST_MATH_SPECIAL_NEGATIVE_BINOMIAL_HPP