binomial.hpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. // boost\math\distributions\binomial.hpp
  2. // Copyright John Maddock 2006.
  3. // Copyright Paul A. Bristow 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/binomial_distribution
  9. // Binomial distribution is the discrete probability distribution of
  10. // the number (k) of successes, in a sequence of
  11. // n independent (yes or no, success or failure) Bernoulli trials.
  12. // It expresses the probability of a number of events occurring in a fixed time
  13. // if these events occur with a known average rate (probability of success),
  14. // and are independent of the time since the last event.
  15. // The number of cars that pass through a certain point on a road during a given period of time.
  16. // The number of spelling mistakes a secretary makes while typing a single page.
  17. // The number of phone calls at a call center per minute.
  18. // The number of times a web server is accessed per minute.
  19. // The number of light bulbs that burn out in a certain amount of time.
  20. // The number of roadkill found per unit length of road
  21. // http://en.wikipedia.org/wiki/binomial_distribution
  22. // Given a sample of N measured values k[i],
  23. // we wish to estimate the value of the parameter x (mean)
  24. // of the binomial population from which the sample was drawn.
  25. // To calculate the maximum likelihood value = 1/N sum i = 1 to N of k[i]
  26. // Also may want a function for EXACTLY k.
  27. // And probability that there are EXACTLY k occurrences is
  28. // exp(-x) * pow(x, k) / factorial(k)
  29. // where x is expected occurrences (mean) during the given interval.
  30. // For example, if events occur, on average, every 4 min,
  31. // and we are interested in number of events occurring in 10 min,
  32. // then x = 10/4 = 2.5
  33. // http://www.itl.nist.gov/div898/handbook/eda/section3/eda366i.htm
  34. // The binomial distribution is used when there are
  35. // exactly two mutually exclusive outcomes of a trial.
  36. // These outcomes are appropriately labeled "success" and "failure".
  37. // The binomial distribution is used to obtain
  38. // the probability of observing x successes in N trials,
  39. // with the probability of success on a single trial denoted by p.
  40. // The binomial distribution assumes that p is fixed for all trials.
  41. // P(x, p, n) = n!/(x! * (n-x)!) * p^x * (1-p)^(n-x)
  42. // http://mathworld.wolfram.com/BinomialCoefficient.html
  43. // The binomial coefficient (n; k) is the number of ways of picking
  44. // k unordered outcomes from n possibilities,
  45. // also known as a combination or combinatorial number.
  46. // The symbols _nC_k and (n; k) are used to denote a binomial coefficient,
  47. // and are sometimes read as "n choose k."
  48. // (n; k) therefore gives the number of k-subsets possible out of a set of n distinct items.
  49. // For example:
  50. // The 2-subsets of {1,2,3,4} are the six pairs {1,2}, {1,3}, {1,4}, {2,3}, {2,4}, and {3,4}, so (4; 2)==6.
  51. // http://functions.wolfram.com/GammaBetaErf/Binomial/ for evaluation.
  52. // But note that the binomial distribution
  53. // (like others including the poisson, negative binomial & Bernoulli)
  54. // is strictly defined as a discrete function: only integral values of k are envisaged.
  55. // However because of the method of calculation using a continuous gamma function,
  56. // it is convenient to treat it as if a continuous function,
  57. // and permit non-integral values of k.
  58. // To enforce the strict mathematical model, users should use floor or ceil functions
  59. // on k outside this function to ensure that k is integral.
  60. #ifndef BOOST_MATH_SPECIAL_BINOMIAL_HPP
  61. #define BOOST_MATH_SPECIAL_BINOMIAL_HPP
  62. #include <boost/math/distributions/fwd.hpp>
  63. #include <boost/math/special_functions/beta.hpp> // for incomplete beta.
  64. #include <boost/math/distributions/complement.hpp> // complements
  65. #include <boost/math/distributions/detail/common_error_handling.hpp> // error checks
  66. #include <boost/math/distributions/detail/inv_discrete_quantile.hpp> // error checks
  67. #include <boost/math/special_functions/fpclassify.hpp> // isnan.
  68. #include <boost/math/tools/roots.hpp> // for root finding.
  69. #include <utility>
  70. namespace boost
  71. {
  72. namespace math
  73. {
  74. template <class RealType, class Policy>
  75. class binomial_distribution;
  76. namespace binomial_detail{
  77. // common error checking routines for binomial distribution functions:
  78. template <class RealType, class Policy>
  79. inline bool check_N(const char* function, const RealType& N, RealType* result, const Policy& pol)
  80. {
  81. if((N < 0) || !(boost::math::isfinite)(N))
  82. {
  83. *result = policies::raise_domain_error<RealType>(
  84. function,
  85. "Number of Trials argument is %1%, but must be >= 0 !", N, pol);
  86. return false;
  87. }
  88. return true;
  89. }
  90. template <class RealType, class Policy>
  91. inline bool check_success_fraction(const char* function, const RealType& p, RealType* result, const Policy& pol)
  92. {
  93. if((p < 0) || (p > 1) || !(boost::math::isfinite)(p))
  94. {
  95. *result = policies::raise_domain_error<RealType>(
  96. function,
  97. "Success fraction argument is %1%, but must be >= 0 and <= 1 !", p, pol);
  98. return false;
  99. }
  100. return true;
  101. }
  102. template <class RealType, class Policy>
  103. inline bool check_dist(const char* function, const RealType& N, const RealType& p, RealType* result, const Policy& pol)
  104. {
  105. return check_success_fraction(
  106. function, p, result, pol)
  107. && check_N(
  108. function, N, result, pol);
  109. }
  110. template <class RealType, class Policy>
  111. inline bool check_dist_and_k(const char* function, const RealType& N, const RealType& p, RealType k, RealType* result, const Policy& pol)
  112. {
  113. if(check_dist(function, N, p, result, pol) == false)
  114. return false;
  115. if((k < 0) || !(boost::math::isfinite)(k))
  116. {
  117. *result = policies::raise_domain_error<RealType>(
  118. function,
  119. "Number of Successes argument is %1%, but must be >= 0 !", k, pol);
  120. return false;
  121. }
  122. if(k > N)
  123. {
  124. *result = policies::raise_domain_error<RealType>(
  125. function,
  126. "Number of Successes argument is %1%, but must be <= Number of Trials !", k, pol);
  127. return false;
  128. }
  129. return true;
  130. }
  131. template <class RealType, class Policy>
  132. inline bool check_dist_and_prob(const char* function, const RealType& N, RealType p, RealType prob, RealType* result, const Policy& pol)
  133. {
  134. if((check_dist(function, N, p, result, pol) && detail::check_probability(function, prob, result, pol)) == false)
  135. return false;
  136. return true;
  137. }
  138. template <class T, class Policy>
  139. T inverse_binomial_cornish_fisher(T n, T sf, T p, T q, const Policy& pol)
  140. {
  141. BOOST_MATH_STD_USING
  142. // mean:
  143. T m = n * sf;
  144. // standard deviation:
  145. T sigma = sqrt(n * sf * (1 - sf));
  146. // skewness
  147. T sk = (1 - 2 * sf) / sigma;
  148. // kurtosis:
  149. // T k = (1 - 6 * sf * (1 - sf) ) / (n * sf * (1 - sf));
  150. // Get the inverse of a std normal distribution:
  151. T x = boost::math::erfc_inv(p > q ? 2 * q : 2 * p, pol) * constants::root_two<T>();
  152. // Set the sign:
  153. if(p < 0.5)
  154. x = -x;
  155. T x2 = x * x;
  156. // w is correction term due to skewness
  157. T w = x + sk * (x2 - 1) / 6;
  158. /*
  159. // Add on correction due to kurtosis.
  160. // Disabled for now, seems to make things worse?
  161. //
  162. if(n >= 10)
  163. w += k * x * (x2 - 3) / 24 + sk * sk * x * (2 * x2 - 5) / -36;
  164. */
  165. w = m + sigma * w;
  166. if(w < tools::min_value<T>())
  167. return sqrt(tools::min_value<T>());
  168. if(w > n)
  169. return n;
  170. return w;
  171. }
  172. template <class RealType, class Policy>
  173. RealType quantile_imp(const binomial_distribution<RealType, Policy>& dist, const RealType& p, const RealType& q, bool comp)
  174. { // Quantile or Percent Point Binomial function.
  175. // Return the number of expected successes k,
  176. // for a given probability p.
  177. //
  178. // Error checks:
  179. BOOST_MATH_STD_USING // ADL of std names
  180. RealType result = 0;
  181. RealType trials = dist.trials();
  182. RealType success_fraction = dist.success_fraction();
  183. if(false == binomial_detail::check_dist_and_prob(
  184. "boost::math::quantile(binomial_distribution<%1%> const&, %1%)",
  185. trials,
  186. success_fraction,
  187. p,
  188. &result, Policy()))
  189. {
  190. return result;
  191. }
  192. // Special cases:
  193. //
  194. if(p == 0)
  195. { // There may actually be no answer to this question,
  196. // since the probability of zero successes may be non-zero,
  197. // but zero is the best we can do:
  198. return 0;
  199. }
  200. if(p == 1 || success_fraction == 1)
  201. { // Probability of n or fewer successes is always one,
  202. // so n is the most sensible answer here:
  203. return trials;
  204. }
  205. if (p <= pow(1 - success_fraction, trials))
  206. { // p <= pdf(dist, 0) == cdf(dist, 0)
  207. return 0; // So the only reasonable result is zero.
  208. } // And root finder would fail otherwise.
  209. // Solve for quantile numerically:
  210. //
  211. RealType guess = binomial_detail::inverse_binomial_cornish_fisher(trials, success_fraction, p, q, Policy());
  212. RealType factor = 8;
  213. if(trials > 100)
  214. factor = 1.01f; // guess is pretty accurate
  215. else if((trials > 10) && (trials - 1 > guess) && (guess > 3))
  216. factor = 1.15f; // less accurate but OK.
  217. else if(trials < 10)
  218. {
  219. // pretty inaccurate guess in this area:
  220. if(guess > trials / 64)
  221. {
  222. guess = trials / 4;
  223. factor = 2;
  224. }
  225. else
  226. guess = trials / 1024;
  227. }
  228. else
  229. factor = 2; // trials largish, but in far tails.
  230. typedef typename Policy::discrete_quantile_type discrete_quantile_type;
  231. std::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
  232. result = detail::inverse_discrete_quantile(
  233. dist,
  234. comp ? q : p,
  235. comp,
  236. guess,
  237. factor,
  238. RealType(1),
  239. discrete_quantile_type(),
  240. max_iter);
  241. return result;
  242. } // quantile
  243. }
  244. template <class RealType = double, class Policy = policies::policy<> >
  245. class binomial_distribution
  246. {
  247. public:
  248. typedef RealType value_type;
  249. typedef Policy policy_type;
  250. binomial_distribution(RealType n = 1, RealType p = 0.5) : m_n(n), m_p(p)
  251. { // Default n = 1 is the Bernoulli distribution
  252. // with equal probability of 'heads' or 'tails.
  253. RealType r;
  254. binomial_detail::check_dist(
  255. "boost::math::binomial_distribution<%1%>::binomial_distribution",
  256. m_n,
  257. m_p,
  258. &r, Policy());
  259. } // binomial_distribution constructor.
  260. RealType success_fraction() const
  261. { // Probability.
  262. return m_p;
  263. }
  264. RealType trials() const
  265. { // Total number of trials.
  266. return m_n;
  267. }
  268. enum interval_type{
  269. clopper_pearson_exact_interval,
  270. jeffreys_prior_interval
  271. };
  272. //
  273. // Estimation of the success fraction parameter.
  274. // The best estimate is actually simply successes/trials,
  275. // these functions are used
  276. // to obtain confidence intervals for the success fraction.
  277. //
  278. static RealType find_lower_bound_on_p(
  279. RealType trials,
  280. RealType successes,
  281. RealType probability,
  282. interval_type t = clopper_pearson_exact_interval)
  283. {
  284. static const char* function = "boost::math::binomial_distribution<%1%>::find_lower_bound_on_p";
  285. // Error checks:
  286. RealType result = 0;
  287. if(false == binomial_detail::check_dist_and_k(
  288. function, trials, RealType(0), successes, &result, Policy())
  289. &&
  290. binomial_detail::check_dist_and_prob(
  291. function, trials, RealType(0), probability, &result, Policy()))
  292. { return result; }
  293. if(successes == 0)
  294. return 0;
  295. // NOTE!!! The Clopper Pearson formula uses "successes" not
  296. // "successes+1" as usual to get the lower bound,
  297. // see http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
  298. return (t == clopper_pearson_exact_interval) ? ibeta_inv(successes, trials - successes + 1, probability, static_cast<RealType*>(nullptr), Policy())
  299. : ibeta_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(nullptr), Policy());
  300. }
  301. static RealType find_upper_bound_on_p(
  302. RealType trials,
  303. RealType successes,
  304. RealType probability,
  305. interval_type t = clopper_pearson_exact_interval)
  306. {
  307. static const char* function = "boost::math::binomial_distribution<%1%>::find_upper_bound_on_p";
  308. // Error checks:
  309. RealType result = 0;
  310. if(false == binomial_detail::check_dist_and_k(
  311. function, trials, RealType(0), successes, &result, Policy())
  312. &&
  313. binomial_detail::check_dist_and_prob(
  314. function, trials, RealType(0), probability, &result, Policy()))
  315. { return result; }
  316. if(trials == successes)
  317. return 1;
  318. return (t == clopper_pearson_exact_interval) ? ibetac_inv(successes + 1, trials - successes, probability, static_cast<RealType*>(nullptr), Policy())
  319. : ibetac_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(nullptr), Policy());
  320. }
  321. // Estimate number of trials parameter:
  322. //
  323. // "How many trials do I need to be P% sure of seeing k events?"
  324. // or
  325. // "How many trials can I have to be P% sure of seeing fewer than k events?"
  326. //
  327. static RealType find_minimum_number_of_trials(
  328. RealType k, // number of events
  329. RealType p, // success fraction
  330. RealType alpha) // risk level
  331. {
  332. static const char* function = "boost::math::binomial_distribution<%1%>::find_minimum_number_of_trials";
  333. // Error checks:
  334. RealType result = 0;
  335. if(false == binomial_detail::check_dist_and_k(
  336. function, k, p, k, &result, Policy())
  337. &&
  338. binomial_detail::check_dist_and_prob(
  339. function, k, p, alpha, &result, Policy()))
  340. { return result; }
  341. result = ibetac_invb(k + 1, p, alpha, Policy()); // returns n - k
  342. return result + k;
  343. }
  344. static RealType find_maximum_number_of_trials(
  345. RealType k, // number of events
  346. RealType p, // success fraction
  347. RealType alpha) // risk level
  348. {
  349. static const char* function = "boost::math::binomial_distribution<%1%>::find_maximum_number_of_trials";
  350. // Error checks:
  351. RealType result = 0;
  352. if(false == binomial_detail::check_dist_and_k(
  353. function, k, p, k, &result, Policy())
  354. &&
  355. binomial_detail::check_dist_and_prob(
  356. function, k, p, alpha, &result, Policy()))
  357. { return result; }
  358. result = ibeta_invb(k + 1, p, alpha, Policy()); // returns n - k
  359. return result + k;
  360. }
  361. private:
  362. RealType m_n; // Not sure if this shouldn't be an int?
  363. RealType m_p; // success_fraction
  364. }; // template <class RealType, class Policy> class binomial_distribution
  365. typedef binomial_distribution<> binomial;
  366. // typedef binomial_distribution<double> binomial;
  367. // IS now included since no longer a name clash with function binomial.
  368. //typedef binomial_distribution<double> binomial; // Reserved name of type double.
  369. #ifdef __cpp_deduction_guides
  370. template <class RealType>
  371. binomial_distribution(RealType)->binomial_distribution<typename boost::math::tools::promote_args<RealType>::type>;
  372. template <class RealType>
  373. binomial_distribution(RealType,RealType)->binomial_distribution<typename boost::math::tools::promote_args<RealType>::type>;
  374. #endif
  375. template <class RealType, class Policy>
  376. const std::pair<RealType, RealType> range(const binomial_distribution<RealType, Policy>& dist)
  377. { // Range of permissible values for random variable k.
  378. using boost::math::tools::max_value;
  379. return std::pair<RealType, RealType>(static_cast<RealType>(0), dist.trials());
  380. }
  381. template <class RealType, class Policy>
  382. const std::pair<RealType, RealType> support(const binomial_distribution<RealType, Policy>& dist)
  383. { // Range of supported values for random variable k.
  384. // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
  385. return std::pair<RealType, RealType>(static_cast<RealType>(0), dist.trials());
  386. }
  387. template <class RealType, class Policy>
  388. inline RealType mean(const binomial_distribution<RealType, Policy>& dist)
  389. { // Mean of Binomial distribution = np.
  390. return dist.trials() * dist.success_fraction();
  391. } // mean
  392. template <class RealType, class Policy>
  393. inline RealType variance(const binomial_distribution<RealType, Policy>& dist)
  394. { // Variance of Binomial distribution = np(1-p).
  395. return dist.trials() * dist.success_fraction() * (1 - dist.success_fraction());
  396. } // variance
  397. template <class RealType, class Policy>
  398. RealType pdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
  399. { // Probability Density/Mass Function.
  400. BOOST_FPU_EXCEPTION_GUARD
  401. BOOST_MATH_STD_USING // for ADL of std functions
  402. RealType n = dist.trials();
  403. // Error check:
  404. RealType result = 0; // initialization silences some compiler warnings
  405. if(false == binomial_detail::check_dist_and_k(
  406. "boost::math::pdf(binomial_distribution<%1%> const&, %1%)",
  407. n,
  408. dist.success_fraction(),
  409. k,
  410. &result, Policy()))
  411. {
  412. return result;
  413. }
  414. // Special cases of success_fraction, regardless of k successes and regardless of n trials.
  415. if (dist.success_fraction() == 0)
  416. { // probability of zero successes is 1:
  417. return static_cast<RealType>(k == 0 ? 1 : 0);
  418. }
  419. if (dist.success_fraction() == 1)
  420. { // probability of n successes is 1:
  421. return static_cast<RealType>(k == n ? 1 : 0);
  422. }
  423. // k argument may be integral, signed, or unsigned, or floating point.
  424. // If necessary, it has already been promoted from an integral type.
  425. if (n == 0)
  426. {
  427. return 1; // Probability = 1 = certainty.
  428. }
  429. if (k == n)
  430. { // binomial coeffic (n n) = 1,
  431. // n ^ 0 = 1
  432. return pow(dist.success_fraction(), k); // * pow((1 - dist.success_fraction()), (n - k)) = 1
  433. }
  434. // Probability of getting exactly k successes
  435. // if C(n, k) is the binomial coefficient then:
  436. //
  437. // f(k; n,p) = C(n, k) * p^k * (1-p)^(n-k)
  438. // = (n!/(k!(n-k)!)) * p^k * (1-p)^(n-k)
  439. // = (tgamma(n+1) / (tgamma(k+1)*tgamma(n-k+1))) * p^k * (1-p)^(n-k)
  440. // = p^k (1-p)^(n-k) / (beta(k+1, n-k+1) * (n+1))
  441. // = ibeta_derivative(k+1, n-k+1, p) / (n+1)
  442. //
  443. using boost::math::ibeta_derivative; // a, b, x
  444. return ibeta_derivative(k+1, n-k+1, dist.success_fraction(), Policy()) / (n+1);
  445. } // pdf
  446. template <class RealType, class Policy>
  447. inline RealType cdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
  448. { // Cumulative Distribution Function Binomial.
  449. // The random variate k is the number of successes in n trials.
  450. // k argument may be integral, signed, or unsigned, or floating point.
  451. // If necessary, it has already been promoted from an integral type.
  452. // Returns the sum of the terms 0 through k of the Binomial Probability Density/Mass:
  453. //
  454. // i=k
  455. // -- ( n ) i n-i
  456. // > | | p (1-p)
  457. // -- ( i )
  458. // i=0
  459. // The terms are not summed directly instead
  460. // the incomplete beta integral is employed,
  461. // according to the formula:
  462. // P = I[1-p]( n-k, k+1).
  463. // = 1 - I[p](k + 1, n - k)
  464. BOOST_MATH_STD_USING // for ADL of std functions
  465. RealType n = dist.trials();
  466. RealType p = dist.success_fraction();
  467. // Error check:
  468. RealType result = 0;
  469. if(false == binomial_detail::check_dist_and_k(
  470. "boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
  471. n,
  472. p,
  473. k,
  474. &result, Policy()))
  475. {
  476. return result;
  477. }
  478. if (k == n)
  479. {
  480. return 1;
  481. }
  482. // Special cases, regardless of k.
  483. if (p == 0)
  484. { // This need explanation:
  485. // the pdf is zero for all cases except when k == 0.
  486. // For zero p the probability of zero successes is one.
  487. // Therefore the cdf is always 1:
  488. // the probability of k or *fewer* successes is always 1
  489. // if there are never any successes!
  490. return 1;
  491. }
  492. if (p == 1)
  493. { // This is correct but needs explanation:
  494. // when k = 1
  495. // all the cdf and pdf values are zero *except* when k == n,
  496. // and that case has been handled above already.
  497. return 0;
  498. }
  499. //
  500. // P = I[1-p](n - k, k + 1)
  501. // = 1 - I[p](k + 1, n - k)
  502. // Use of ibetac here prevents cancellation errors in calculating
  503. // 1-p if p is very small, perhaps smaller than machine epsilon.
  504. //
  505. // Note that we do not use a finite sum here, since the incomplete
  506. // beta uses a finite sum internally for integer arguments, so
  507. // we'll just let it take care of the necessary logic.
  508. //
  509. return ibetac(k + 1, n - k, p, Policy());
  510. } // binomial cdf
  511. template <class RealType, class Policy>
  512. inline RealType cdf(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
  513. { // Complemented Cumulative Distribution Function Binomial.
  514. // The random variate k is the number of successes in n trials.
  515. // k argument may be integral, signed, or unsigned, or floating point.
  516. // If necessary, it has already been promoted from an integral type.
  517. // Returns the sum of the terms k+1 through n of the Binomial Probability Density/Mass:
  518. //
  519. // i=n
  520. // -- ( n ) i n-i
  521. // > | | p (1-p)
  522. // -- ( i )
  523. // i=k+1
  524. // The terms are not summed directly instead
  525. // the incomplete beta integral is employed,
  526. // according to the formula:
  527. // Q = 1 -I[1-p]( n-k, k+1).
  528. // = I[p](k + 1, n - k)
  529. BOOST_MATH_STD_USING // for ADL of std functions
  530. RealType const& k = c.param;
  531. binomial_distribution<RealType, Policy> const& dist = c.dist;
  532. RealType n = dist.trials();
  533. RealType p = dist.success_fraction();
  534. // Error checks:
  535. RealType result = 0;
  536. if(false == binomial_detail::check_dist_and_k(
  537. "boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
  538. n,
  539. p,
  540. k,
  541. &result, Policy()))
  542. {
  543. return result;
  544. }
  545. if (k == n)
  546. { // Probability of greater than n successes is necessarily zero:
  547. return 0;
  548. }
  549. // Special cases, regardless of k.
  550. if (p == 0)
  551. {
  552. // This need explanation: the pdf is zero for all
  553. // cases except when k == 0. For zero p the probability
  554. // of zero successes is one. Therefore the cdf is always
  555. // 1: the probability of *more than* k successes is always 0
  556. // if there are never any successes!
  557. return 0;
  558. }
  559. if (p == 1)
  560. {
  561. // This needs explanation, when p = 1
  562. // we always have n successes, so the probability
  563. // of more than k successes is 1 as long as k < n.
  564. // The k == n case has already been handled above.
  565. return 1;
  566. }
  567. //
  568. // Calculate cdf binomial using the incomplete beta function.
  569. // Q = 1 -I[1-p](n - k, k + 1)
  570. // = I[p](k + 1, n - k)
  571. // Use of ibeta here prevents cancellation errors in calculating
  572. // 1-p if p is very small, perhaps smaller than machine epsilon.
  573. //
  574. // Note that we do not use a finite sum here, since the incomplete
  575. // beta uses a finite sum internally for integer arguments, so
  576. // we'll just let it take care of the necessary logic.
  577. //
  578. return ibeta(k + 1, n - k, p, Policy());
  579. } // binomial cdf
  580. template <class RealType, class Policy>
  581. inline RealType quantile(const binomial_distribution<RealType, Policy>& dist, const RealType& p)
  582. {
  583. return binomial_detail::quantile_imp(dist, p, RealType(1-p), false);
  584. } // quantile
  585. template <class RealType, class Policy>
  586. RealType quantile(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
  587. {
  588. return binomial_detail::quantile_imp(c.dist, RealType(1-c.param), c.param, true);
  589. } // quantile
  590. template <class RealType, class Policy>
  591. inline RealType mode(const binomial_distribution<RealType, Policy>& dist)
  592. {
  593. BOOST_MATH_STD_USING // ADL of std functions.
  594. RealType p = dist.success_fraction();
  595. RealType n = dist.trials();
  596. return floor(p * (n + 1));
  597. }
  598. template <class RealType, class Policy>
  599. inline RealType median(const binomial_distribution<RealType, Policy>& dist)
  600. { // Bounds for the median of the negative binomial distribution
  601. // VAN DE VEN R. ; WEBER N. C. ;
  602. // Univ. Sydney, school mathematics statistics, Sydney N.S.W. 2006, AUSTRALIE
  603. // Metrika (Metrika) ISSN 0026-1335 CODEN MTRKA8
  604. // 1993, vol. 40, no3-4, pp. 185-189 (4 ref.)
  605. // Bounds for median and 50 percentage point of binomial and negative binomial distribution
  606. // Metrika, ISSN 0026-1335 (Print) 1435-926X (Online)
  607. // Volume 41, Number 1 / December, 1994, DOI 10.1007/BF01895303
  608. BOOST_MATH_STD_USING // ADL of std functions.
  609. RealType p = dist.success_fraction();
  610. RealType n = dist.trials();
  611. // Wikipedia says one of floor(np) -1, floor (np), floor(np) +1
  612. return floor(p * n); // Chose the middle value.
  613. }
  614. template <class RealType, class Policy>
  615. inline RealType skewness(const binomial_distribution<RealType, Policy>& dist)
  616. {
  617. BOOST_MATH_STD_USING // ADL of std functions.
  618. RealType p = dist.success_fraction();
  619. RealType n = dist.trials();
  620. return (1 - 2 * p) / sqrt(n * p * (1 - p));
  621. }
  622. template <class RealType, class Policy>
  623. inline RealType kurtosis(const binomial_distribution<RealType, Policy>& dist)
  624. {
  625. RealType p = dist.success_fraction();
  626. RealType n = dist.trials();
  627. return 3 - 6 / n + 1 / (n * p * (1 - p));
  628. }
  629. template <class RealType, class Policy>
  630. inline RealType kurtosis_excess(const binomial_distribution<RealType, Policy>& dist)
  631. {
  632. RealType p = dist.success_fraction();
  633. RealType q = 1 - p;
  634. RealType n = dist.trials();
  635. return (1 - 6 * p * q) / (n * p * q);
  636. }
  637. } // namespace math
  638. } // namespace boost
  639. // This include must be at the end, *after* the accessors
  640. // for this distribution have been defined, in order to
  641. // keep compilers that support two-phase lookup happy.
  642. #include <boost/math/distributions/detail/derived_accessors.hpp>
  643. #endif // BOOST_MATH_SPECIAL_BINOMIAL_HPP