binomial.hpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. return 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. } // quantile
  242. }
  243. template <class RealType = double, class Policy = policies::policy<> >
  244. class binomial_distribution
  245. {
  246. public:
  247. typedef RealType value_type;
  248. typedef Policy policy_type;
  249. binomial_distribution(RealType n = 1, RealType p = 0.5) : m_n(n), m_p(p)
  250. { // Default n = 1 is the Bernoulli distribution
  251. // with equal probability of 'heads' or 'tails.
  252. RealType r;
  253. binomial_detail::check_dist(
  254. "boost::math::binomial_distribution<%1%>::binomial_distribution",
  255. m_n,
  256. m_p,
  257. &r, Policy());
  258. } // binomial_distribution constructor.
  259. RealType success_fraction() const
  260. { // Probability.
  261. return m_p;
  262. }
  263. RealType trials() const
  264. { // Total number of trials.
  265. return m_n;
  266. }
  267. enum interval_type{
  268. clopper_pearson_exact_interval,
  269. jeffreys_prior_interval
  270. };
  271. //
  272. // Estimation of the success fraction parameter.
  273. // The best estimate is actually simply successes/trials,
  274. // these functions are used
  275. // to obtain confidence intervals for the success fraction.
  276. //
  277. static RealType find_lower_bound_on_p(
  278. RealType trials,
  279. RealType successes,
  280. RealType probability,
  281. interval_type t = clopper_pearson_exact_interval)
  282. {
  283. static const char* function = "boost::math::binomial_distribution<%1%>::find_lower_bound_on_p";
  284. // Error checks:
  285. RealType result = 0;
  286. if(false == binomial_detail::check_dist_and_k(
  287. function, trials, RealType(0), successes, &result, Policy())
  288. &&
  289. binomial_detail::check_dist_and_prob(
  290. function, trials, RealType(0), probability, &result, Policy()))
  291. { return result; }
  292. if(successes == 0)
  293. return 0;
  294. // NOTE!!! The Clopper Pearson formula uses "successes" not
  295. // "successes+1" as usual to get the lower bound,
  296. // see http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
  297. return (t == clopper_pearson_exact_interval) ? ibeta_inv(successes, trials - successes + 1, probability, static_cast<RealType*>(nullptr), Policy())
  298. : ibeta_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(nullptr), Policy());
  299. }
  300. static RealType find_upper_bound_on_p(
  301. RealType trials,
  302. RealType successes,
  303. RealType probability,
  304. interval_type t = clopper_pearson_exact_interval)
  305. {
  306. static const char* function = "boost::math::binomial_distribution<%1%>::find_upper_bound_on_p";
  307. // Error checks:
  308. RealType result = 0;
  309. if(false == binomial_detail::check_dist_and_k(
  310. function, trials, RealType(0), successes, &result, Policy())
  311. &&
  312. binomial_detail::check_dist_and_prob(
  313. function, trials, RealType(0), probability, &result, Policy()))
  314. { return result; }
  315. if(trials == successes)
  316. return 1;
  317. return (t == clopper_pearson_exact_interval) ? ibetac_inv(successes + 1, trials - successes, probability, static_cast<RealType*>(nullptr), Policy())
  318. : ibetac_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(nullptr), Policy());
  319. }
  320. // Estimate number of trials parameter:
  321. //
  322. // "How many trials do I need to be P% sure of seeing k events?"
  323. // or
  324. // "How many trials can I have to be P% sure of seeing fewer than k events?"
  325. //
  326. static RealType find_minimum_number_of_trials(
  327. RealType k, // number of events
  328. RealType p, // success fraction
  329. RealType alpha) // risk level
  330. {
  331. static const char* function = "boost::math::binomial_distribution<%1%>::find_minimum_number_of_trials";
  332. // Error checks:
  333. RealType result = 0;
  334. if(false == binomial_detail::check_dist_and_k(
  335. function, k, p, k, &result, Policy())
  336. &&
  337. binomial_detail::check_dist_and_prob(
  338. function, k, p, alpha, &result, Policy()))
  339. { return result; }
  340. result = ibetac_invb(k + 1, p, alpha, Policy()); // returns n - k
  341. return result + k;
  342. }
  343. static RealType find_maximum_number_of_trials(
  344. RealType k, // number of events
  345. RealType p, // success fraction
  346. RealType alpha) // risk level
  347. {
  348. static const char* function = "boost::math::binomial_distribution<%1%>::find_maximum_number_of_trials";
  349. // Error checks:
  350. RealType result = 0;
  351. if(false == binomial_detail::check_dist_and_k(
  352. function, k, p, k, &result, Policy())
  353. &&
  354. binomial_detail::check_dist_and_prob(
  355. function, k, p, alpha, &result, Policy()))
  356. { return result; }
  357. result = ibeta_invb(k + 1, p, alpha, Policy()); // returns n - k
  358. return result + k;
  359. }
  360. private:
  361. RealType m_n; // Not sure if this shouldn't be an int?
  362. RealType m_p; // success_fraction
  363. }; // template <class RealType, class Policy> class binomial_distribution
  364. typedef binomial_distribution<> binomial;
  365. // typedef binomial_distribution<double> binomial;
  366. // IS now included since no longer a name clash with function binomial.
  367. //typedef binomial_distribution<double> binomial; // Reserved name of type double.
  368. #ifdef __cpp_deduction_guides
  369. template <class RealType>
  370. binomial_distribution(RealType)->binomial_distribution<typename boost::math::tools::promote_args<RealType>::type>;
  371. template <class RealType>
  372. binomial_distribution(RealType,RealType)->binomial_distribution<typename boost::math::tools::promote_args<RealType>::type>;
  373. #endif
  374. template <class RealType, class Policy>
  375. const std::pair<RealType, RealType> range(const binomial_distribution<RealType, Policy>& dist)
  376. { // Range of permissible values for random variable k.
  377. using boost::math::tools::max_value;
  378. return std::pair<RealType, RealType>(static_cast<RealType>(0), dist.trials());
  379. }
  380. template <class RealType, class Policy>
  381. const std::pair<RealType, RealType> support(const binomial_distribution<RealType, Policy>& dist)
  382. { // Range of supported values for random variable k.
  383. // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
  384. return std::pair<RealType, RealType>(static_cast<RealType>(0), dist.trials());
  385. }
  386. template <class RealType, class Policy>
  387. inline RealType mean(const binomial_distribution<RealType, Policy>& dist)
  388. { // Mean of Binomial distribution = np.
  389. return dist.trials() * dist.success_fraction();
  390. } // mean
  391. template <class RealType, class Policy>
  392. inline RealType variance(const binomial_distribution<RealType, Policy>& dist)
  393. { // Variance of Binomial distribution = np(1-p).
  394. return dist.trials() * dist.success_fraction() * (1 - dist.success_fraction());
  395. } // variance
  396. template <class RealType, class Policy>
  397. RealType pdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
  398. { // Probability Density/Mass Function.
  399. BOOST_FPU_EXCEPTION_GUARD
  400. BOOST_MATH_STD_USING // for ADL of std functions
  401. RealType n = dist.trials();
  402. // Error check:
  403. RealType result = 0; // initialization silences some compiler warnings
  404. if(false == binomial_detail::check_dist_and_k(
  405. "boost::math::pdf(binomial_distribution<%1%> const&, %1%)",
  406. n,
  407. dist.success_fraction(),
  408. k,
  409. &result, Policy()))
  410. {
  411. return result;
  412. }
  413. // Special cases of success_fraction, regardless of k successes and regardless of n trials.
  414. if (dist.success_fraction() == 0)
  415. { // probability of zero successes is 1:
  416. return static_cast<RealType>(k == 0 ? 1 : 0);
  417. }
  418. if (dist.success_fraction() == 1)
  419. { // probability of n successes is 1:
  420. return static_cast<RealType>(k == n ? 1 : 0);
  421. }
  422. // k argument may be integral, signed, or unsigned, or floating point.
  423. // If necessary, it has already been promoted from an integral type.
  424. if (n == 0)
  425. {
  426. return 1; // Probability = 1 = certainty.
  427. }
  428. if (k == n)
  429. { // binomial coeffic (n n) = 1,
  430. // n ^ 0 = 1
  431. return pow(dist.success_fraction(), k); // * pow((1 - dist.success_fraction()), (n - k)) = 1
  432. }
  433. // Probability of getting exactly k successes
  434. // if C(n, k) is the binomial coefficient then:
  435. //
  436. // f(k; n,p) = C(n, k) * p^k * (1-p)^(n-k)
  437. // = (n!/(k!(n-k)!)) * p^k * (1-p)^(n-k)
  438. // = (tgamma(n+1) / (tgamma(k+1)*tgamma(n-k+1))) * p^k * (1-p)^(n-k)
  439. // = p^k (1-p)^(n-k) / (beta(k+1, n-k+1) * (n+1))
  440. // = ibeta_derivative(k+1, n-k+1, p) / (n+1)
  441. //
  442. using boost::math::ibeta_derivative; // a, b, x
  443. return ibeta_derivative(k+1, n-k+1, dist.success_fraction(), Policy()) / (n+1);
  444. } // pdf
  445. template <class RealType, class Policy>
  446. inline RealType cdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
  447. { // Cumulative Distribution Function Binomial.
  448. // The random variate k is the number of successes in n trials.
  449. // k argument may be integral, signed, or unsigned, or floating point.
  450. // If necessary, it has already been promoted from an integral type.
  451. // Returns the sum of the terms 0 through k of the Binomial Probability Density/Mass:
  452. //
  453. // i=k
  454. // -- ( n ) i n-i
  455. // > | | p (1-p)
  456. // -- ( i )
  457. // i=0
  458. // The terms are not summed directly instead
  459. // the incomplete beta integral is employed,
  460. // according to the formula:
  461. // P = I[1-p]( n-k, k+1).
  462. // = 1 - I[p](k + 1, n - k)
  463. BOOST_MATH_STD_USING // for ADL of std functions
  464. RealType n = dist.trials();
  465. RealType p = dist.success_fraction();
  466. // Error check:
  467. RealType result = 0;
  468. if(false == binomial_detail::check_dist_and_k(
  469. "boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
  470. n,
  471. p,
  472. k,
  473. &result, Policy()))
  474. {
  475. return result;
  476. }
  477. if (k == n)
  478. {
  479. return 1;
  480. }
  481. // Special cases, regardless of k.
  482. if (p == 0)
  483. { // This need explanation:
  484. // the pdf is zero for all cases except when k == 0.
  485. // For zero p the probability of zero successes is one.
  486. // Therefore the cdf is always 1:
  487. // the probability of k or *fewer* successes is always 1
  488. // if there are never any successes!
  489. return 1;
  490. }
  491. if (p == 1)
  492. { // This is correct but needs explanation:
  493. // when k = 1
  494. // all the cdf and pdf values are zero *except* when k == n,
  495. // and that case has been handled above already.
  496. return 0;
  497. }
  498. //
  499. // P = I[1-p](n - k, k + 1)
  500. // = 1 - I[p](k + 1, n - k)
  501. // Use of ibetac here prevents cancellation errors in calculating
  502. // 1-p if p is very small, perhaps smaller than machine epsilon.
  503. //
  504. // Note that we do not use a finite sum here, since the incomplete
  505. // beta uses a finite sum internally for integer arguments, so
  506. // we'll just let it take care of the necessary logic.
  507. //
  508. return ibetac(k + 1, n - k, p, Policy());
  509. } // binomial cdf
  510. template <class RealType, class Policy>
  511. inline RealType cdf(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
  512. { // Complemented Cumulative Distribution Function Binomial.
  513. // The random variate k is the number of successes in n trials.
  514. // k argument may be integral, signed, or unsigned, or floating point.
  515. // If necessary, it has already been promoted from an integral type.
  516. // Returns the sum of the terms k+1 through n of the Binomial Probability Density/Mass:
  517. //
  518. // i=n
  519. // -- ( n ) i n-i
  520. // > | | p (1-p)
  521. // -- ( i )
  522. // i=k+1
  523. // The terms are not summed directly instead
  524. // the incomplete beta integral is employed,
  525. // according to the formula:
  526. // Q = 1 -I[1-p]( n-k, k+1).
  527. // = I[p](k + 1, n - k)
  528. BOOST_MATH_STD_USING // for ADL of std functions
  529. RealType const& k = c.param;
  530. binomial_distribution<RealType, Policy> const& dist = c.dist;
  531. RealType n = dist.trials();
  532. RealType p = dist.success_fraction();
  533. // Error checks:
  534. RealType result = 0;
  535. if(false == binomial_detail::check_dist_and_k(
  536. "boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
  537. n,
  538. p,
  539. k,
  540. &result, Policy()))
  541. {
  542. return result;
  543. }
  544. if (k == n)
  545. { // Probability of greater than n successes is necessarily zero:
  546. return 0;
  547. }
  548. // Special cases, regardless of k.
  549. if (p == 0)
  550. {
  551. // This need explanation: the pdf is zero for all
  552. // cases except when k == 0. For zero p the probability
  553. // of zero successes is one. Therefore the cdf is always
  554. // 1: the probability of *more than* k successes is always 0
  555. // if there are never any successes!
  556. return 0;
  557. }
  558. if (p == 1)
  559. {
  560. // This needs explanation, when p = 1
  561. // we always have n successes, so the probability
  562. // of more than k successes is 1 as long as k < n.
  563. // The k == n case has already been handled above.
  564. return 1;
  565. }
  566. //
  567. // Calculate cdf binomial using the incomplete beta function.
  568. // Q = 1 -I[1-p](n - k, k + 1)
  569. // = I[p](k + 1, n - k)
  570. // Use of ibeta here prevents cancellation errors in calculating
  571. // 1-p if p is very small, perhaps smaller than machine epsilon.
  572. //
  573. // Note that we do not use a finite sum here, since the incomplete
  574. // beta uses a finite sum internally for integer arguments, so
  575. // we'll just let it take care of the necessary logic.
  576. //
  577. return ibeta(k + 1, n - k, p, Policy());
  578. } // binomial cdf
  579. template <class RealType, class Policy>
  580. inline RealType quantile(const binomial_distribution<RealType, Policy>& dist, const RealType& p)
  581. {
  582. return binomial_detail::quantile_imp(dist, p, RealType(1-p), false);
  583. } // quantile
  584. template <class RealType, class Policy>
  585. RealType quantile(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
  586. {
  587. return binomial_detail::quantile_imp(c.dist, RealType(1-c.param), c.param, true);
  588. } // quantile
  589. template <class RealType, class Policy>
  590. inline RealType mode(const binomial_distribution<RealType, Policy>& dist)
  591. {
  592. BOOST_MATH_STD_USING // ADL of std functions.
  593. RealType p = dist.success_fraction();
  594. RealType n = dist.trials();
  595. return floor(p * (n + 1));
  596. }
  597. template <class RealType, class Policy>
  598. inline RealType median(const binomial_distribution<RealType, Policy>& dist)
  599. { // Bounds for the median of the negative binomial distribution
  600. // VAN DE VEN R. ; WEBER N. C. ;
  601. // Univ. Sydney, school mathematics statistics, Sydney N.S.W. 2006, AUSTRALIE
  602. // Metrika (Metrika) ISSN 0026-1335 CODEN MTRKA8
  603. // 1993, vol. 40, no3-4, pp. 185-189 (4 ref.)
  604. // Bounds for median and 50 percentage point of binomial and negative binomial distribution
  605. // Metrika, ISSN 0026-1335 (Print) 1435-926X (Online)
  606. // Volume 41, Number 1 / December, 1994, DOI 10.1007/BF01895303
  607. BOOST_MATH_STD_USING // ADL of std functions.
  608. RealType p = dist.success_fraction();
  609. RealType n = dist.trials();
  610. // Wikipedia says one of floor(np) -1, floor (np), floor(np) +1
  611. return floor(p * n); // Chose the middle value.
  612. }
  613. template <class RealType, class Policy>
  614. inline RealType skewness(const binomial_distribution<RealType, Policy>& dist)
  615. {
  616. BOOST_MATH_STD_USING // ADL of std functions.
  617. RealType p = dist.success_fraction();
  618. RealType n = dist.trials();
  619. return (1 - 2 * p) / sqrt(n * p * (1 - p));
  620. }
  621. template <class RealType, class Policy>
  622. inline RealType kurtosis(const binomial_distribution<RealType, Policy>& dist)
  623. {
  624. RealType p = dist.success_fraction();
  625. RealType n = dist.trials();
  626. return 3 - 6 / n + 1 / (n * p * (1 - p));
  627. }
  628. template <class RealType, class Policy>
  629. inline RealType kurtosis_excess(const binomial_distribution<RealType, Policy>& dist)
  630. {
  631. RealType p = dist.success_fraction();
  632. RealType q = 1 - p;
  633. RealType n = dist.trials();
  634. return (1 - 6 * p * q) / (n * p * q);
  635. }
  636. } // namespace math
  637. } // namespace boost
  638. // This include must be at the end, *after* the accessors
  639. // for this distribution have been defined, in order to
  640. // keep compilers that support two-phase lookup happy.
  641. #include <boost/math/distributions/detail/derived_accessors.hpp>
  642. #endif // BOOST_MATH_SPECIAL_BINOMIAL_HPP