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. // precede 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 continuous 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 <limits> // using std::numeric_limits;
  43. #include <utility>
  44. #if defined (BOOST_MSVC)
  45. # pragma warning(push)
  46. // This believed not now necessary, so commented out.
  47. //# pragma warning(disable: 4702) // unreachable code.
  48. // in domain_error_imp in error_handling.
  49. #endif
  50. namespace boost
  51. {
  52. namespace math
  53. {
  54. namespace negative_binomial_detail
  55. {
  56. // Common error checking routines for negative binomial distribution functions:
  57. template <class RealType, class Policy>
  58. inline bool check_successes(const char* function, const RealType& r, RealType* result, const Policy& pol)
  59. {
  60. if( !(boost::math::isfinite)(r) || (r <= 0) )
  61. {
  62. *result = policies::raise_domain_error<RealType>(
  63. function,
  64. "Number of successes argument is %1%, but must be > 0 !", r, pol);
  65. return false;
  66. }
  67. return true;
  68. }
  69. template <class RealType, class Policy>
  70. inline bool check_success_fraction(const char* function, const RealType& p, RealType* result, const Policy& pol)
  71. {
  72. if( !(boost::math::isfinite)(p) || (p < 0) || (p > 1) )
  73. {
  74. *result = policies::raise_domain_error<RealType>(
  75. function,
  76. "Success fraction argument is %1%, but must be >= 0 and <= 1 !", p, pol);
  77. return false;
  78. }
  79. return true;
  80. }
  81. template <class RealType, class Policy>
  82. inline bool check_dist(const char* function, const RealType& r, const RealType& p, RealType* result, const Policy& pol)
  83. {
  84. return check_success_fraction(function, p, result, pol)
  85. && check_successes(function, r, result, pol);
  86. }
  87. template <class RealType, class Policy>
  88. inline bool check_dist_and_k(const char* function, const RealType& r, const RealType& p, RealType k, RealType* result, const Policy& pol)
  89. {
  90. if(check_dist(function, r, p, result, pol) == false)
  91. {
  92. return false;
  93. }
  94. if( !(boost::math::isfinite)(k) || (k < 0) )
  95. { // Check k failures.
  96. *result = policies::raise_domain_error<RealType>(
  97. function,
  98. "Number of failures argument is %1%, but must be >= 0 !", k, pol);
  99. return false;
  100. }
  101. return true;
  102. } // Check_dist_and_k
  103. template <class RealType, class Policy>
  104. inline bool check_dist_and_prob(const char* function, const RealType& r, RealType p, RealType prob, RealType* result, const Policy& pol)
  105. {
  106. if((check_dist(function, r, p, result, pol) && detail::check_probability(function, prob, result, pol)) == false)
  107. {
  108. return false;
  109. }
  110. return true;
  111. } // check_dist_and_prob
  112. } // namespace negative_binomial_detail
  113. template <class RealType = double, class Policy = policies::policy<> >
  114. class negative_binomial_distribution
  115. {
  116. public:
  117. typedef RealType value_type;
  118. typedef Policy policy_type;
  119. negative_binomial_distribution(RealType r, RealType p) : m_r(r), m_p(p)
  120. { // Constructor.
  121. RealType result;
  122. negative_binomial_detail::check_dist(
  123. "negative_binomial_distribution<%1%>::negative_binomial_distribution",
  124. m_r, // Check successes r > 0.
  125. m_p, // Check success_fraction 0 <= p <= 1.
  126. &result, Policy());
  127. } // negative_binomial_distribution constructor.
  128. // Private data getter class member functions.
  129. RealType success_fraction() const
  130. { // Probability of success as fraction in range 0 to 1.
  131. return m_p;
  132. }
  133. RealType successes() const
  134. { // Total number of successes r.
  135. return m_r;
  136. }
  137. static RealType find_lower_bound_on_p(
  138. RealType trials,
  139. RealType successes,
  140. RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.
  141. {
  142. static const char* function = "boost::math::negative_binomial<%1%>::find_lower_bound_on_p";
  143. RealType result = 0; // of error checks.
  144. RealType failures = trials - successes;
  145. if(false == detail::check_probability(function, alpha, &result, Policy())
  146. && negative_binomial_detail::check_dist_and_k(
  147. function, successes, RealType(0), failures, &result, Policy()))
  148. {
  149. return result;
  150. }
  151. // Use complement ibeta_inv function for lower bound.
  152. // This is adapted from the corresponding binomial formula
  153. // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
  154. // This is a Clopper-Pearson interval, and may be overly conservative,
  155. // see also "A Simple Improved Inferential Method for Some
  156. // Discrete Distributions" Yong CAI and K. KRISHNAMOORTHY
  157. // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf
  158. //
  159. return ibeta_inv(successes, failures + 1, alpha, static_cast<RealType*>(nullptr), Policy());
  160. } // find_lower_bound_on_p
  161. static RealType find_upper_bound_on_p(
  162. RealType trials,
  163. RealType successes,
  164. RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.
  165. {
  166. static const char* function = "boost::math::negative_binomial<%1%>::find_upper_bound_on_p";
  167. RealType result = 0; // of error checks.
  168. RealType failures = trials - successes;
  169. if(false == negative_binomial_detail::check_dist_and_k(
  170. function, successes, RealType(0), failures, &result, Policy())
  171. && detail::check_probability(function, alpha, &result, Policy()))
  172. {
  173. return result;
  174. }
  175. if(failures == 0)
  176. return 1;
  177. // Use complement ibetac_inv function for upper bound.
  178. // Note adjusted failures value: *not* failures+1 as usual.
  179. // This is adapted from the corresponding binomial formula
  180. // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
  181. // This is a Clopper-Pearson interval, and may be overly conservative,
  182. // see also "A Simple Improved Inferential Method for Some
  183. // Discrete Distributions" Yong CAI and K. KRISHNAMOORTHY
  184. // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf
  185. //
  186. return ibetac_inv(successes, failures, alpha, static_cast<RealType*>(nullptr), Policy());
  187. } // find_upper_bound_on_p
  188. // Estimate number of trials :
  189. // "How many trials do I need to be P% sure of seeing k or fewer failures?"
  190. static RealType find_minimum_number_of_trials(
  191. RealType k, // number of failures (k >= 0).
  192. RealType p, // success fraction 0 <= p <= 1.
  193. RealType alpha) // risk level threshold 0 <= alpha <= 1.
  194. {
  195. static const char* function = "boost::math::negative_binomial<%1%>::find_minimum_number_of_trials";
  196. // Error checks:
  197. RealType result = 0;
  198. if(false == negative_binomial_detail::check_dist_and_k(
  199. function, RealType(1), p, k, &result, Policy())
  200. && detail::check_probability(function, alpha, &result, Policy()))
  201. { return result; }
  202. result = ibeta_inva(k + 1, p, alpha, Policy()); // returns n - k
  203. return result + k;
  204. } // RealType find_number_of_failures
  205. static RealType find_maximum_number_of_trials(
  206. RealType k, // number of failures (k >= 0).
  207. RealType p, // success fraction 0 <= p <= 1.
  208. RealType alpha) // risk level threshold 0 <= alpha <= 1.
  209. {
  210. static const char* function = "boost::math::negative_binomial<%1%>::find_maximum_number_of_trials";
  211. // Error checks:
  212. RealType result = 0;
  213. if(false == negative_binomial_detail::check_dist_and_k(
  214. function, RealType(1), p, k, &result, Policy())
  215. && detail::check_probability(function, alpha, &result, Policy()))
  216. { return result; }
  217. result = ibetac_inva(k + 1, p, alpha, Policy()); // returns n - k
  218. return result + k;
  219. } // RealType find_number_of_trials complemented
  220. private:
  221. RealType m_r; // successes.
  222. RealType m_p; // success_fraction
  223. }; // template <class RealType, class Policy> class negative_binomial_distribution
  224. typedef negative_binomial_distribution<double> negative_binomial; // Reserved name of type double.
  225. #ifdef __cpp_deduction_guides
  226. template <class RealType>
  227. negative_binomial_distribution(RealType,RealType)->negative_binomial_distribution<typename boost::math::tools::promote_args<RealType>::type>;
  228. #endif
  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. std::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. std::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