Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-07-11 08:14:56

0001 // boost\math\distributions\binomial.hpp
0002 
0003 // Copyright John Maddock 2006.
0004 // Copyright Paul A. Bristow 2007.
0005 
0006 // Use, modification and distribution are subject to the
0007 // Boost Software License, Version 1.0.
0008 // (See accompanying file LICENSE_1_0.txt
0009 // or copy at http://www.boost.org/LICENSE_1_0.txt)
0010 
0011 // http://en.wikipedia.org/wiki/binomial_distribution
0012 
0013 // Binomial distribution is the discrete probability distribution of
0014 // the number (k) of successes, in a sequence of
0015 // n independent (yes or no, success or failure) Bernoulli trials.
0016 
0017 // It expresses the probability of a number of events occurring in a fixed time
0018 // if these events occur with a known average rate (probability of success),
0019 // and are independent of the time since the last event.
0020 
0021 // The number of cars that pass through a certain point on a road during a given period of time.
0022 // The number of spelling mistakes a secretary makes while typing a single page.
0023 // The number of phone calls at a call center per minute.
0024 // The number of times a web server is accessed per minute.
0025 // The number of light bulbs that burn out in a certain amount of time.
0026 // The number of roadkill found per unit length of road
0027 
0028 // http://en.wikipedia.org/wiki/binomial_distribution
0029 
0030 // Given a sample of N measured values k[i],
0031 // we wish to estimate the value of the parameter x (mean)
0032 // of the binomial population from which the sample was drawn.
0033 // To calculate the maximum likelihood value = 1/N sum i = 1 to N of k[i]
0034 
0035 // Also may want a function for EXACTLY k.
0036 
0037 // And probability that there are EXACTLY k occurrences is
0038 // exp(-x) * pow(x, k) / factorial(k)
0039 // where x is expected occurrences (mean) during the given interval.
0040 // For example, if events occur, on average, every 4 min,
0041 // and we are interested in number of events occurring in 10 min,
0042 // then x = 10/4 = 2.5
0043 
0044 // http://www.itl.nist.gov/div898/handbook/eda/section3/eda366i.htm
0045 
0046 // The binomial distribution is used when there are
0047 // exactly two mutually exclusive outcomes of a trial.
0048 // These outcomes are appropriately labeled "success" and "failure".
0049 // The binomial distribution is used to obtain
0050 // the probability of observing x successes in N trials,
0051 // with the probability of success on a single trial denoted by p.
0052 // The binomial distribution assumes that p is fixed for all trials.
0053 
0054 // P(x, p, n) = n!/(x! * (n-x)!) * p^x * (1-p)^(n-x)
0055 
0056 // http://mathworld.wolfram.com/BinomialCoefficient.html
0057 
0058 // The binomial coefficient (n; k) is the number of ways of picking
0059 // k unordered outcomes from n possibilities,
0060 // also known as a combination or combinatorial number.
0061 // The symbols _nC_k and (n; k) are used to denote a binomial coefficient,
0062 // and are sometimes read as "n choose k."
0063 // (n; k) therefore gives the number of k-subsets  possible out of a set of n distinct items.
0064 
0065 // For example:
0066 //  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.
0067 
0068 // http://functions.wolfram.com/GammaBetaErf/Binomial/ for evaluation.
0069 
0070 // But note that the binomial distribution
0071 // (like others including the poisson, negative binomial & Bernoulli)
0072 // is strictly defined as a discrete function: only integral values of k are envisaged.
0073 // However because of the method of calculation using a continuous gamma function,
0074 // it is convenient to treat it as if a continuous function,
0075 // and permit non-integral values of k.
0076 // To enforce the strict mathematical model, users should use floor or ceil functions
0077 // on k outside this function to ensure that k is integral.
0078 
0079 #ifndef BOOST_MATH_SPECIAL_BINOMIAL_HPP
0080 #define BOOST_MATH_SPECIAL_BINOMIAL_HPP
0081 
0082 #include <boost/math/distributions/fwd.hpp>
0083 #include <boost/math/special_functions/beta.hpp> // for incomplete beta.
0084 #include <boost/math/distributions/complement.hpp> // complements
0085 #include <boost/math/distributions/detail/common_error_handling.hpp> // error checks
0086 #include <boost/math/distributions/detail/inv_discrete_quantile.hpp> // error checks
0087 #include <boost/math/special_functions/fpclassify.hpp> // isnan.
0088 #include <boost/math/tools/roots.hpp> // for root finding.
0089 
0090 #include <utility>
0091 
0092 namespace boost
0093 {
0094   namespace math
0095   {
0096 
0097      template <class RealType, class Policy>
0098      class binomial_distribution;
0099 
0100      namespace binomial_detail{
0101         // common error checking routines for binomial distribution functions:
0102         template <class RealType, class Policy>
0103         inline bool check_N(const char* function, const RealType& N, RealType* result, const Policy& pol)
0104         {
0105            if((N < 0) || !(boost::math::isfinite)(N))
0106            {
0107                *result = policies::raise_domain_error<RealType>(
0108                   function,
0109                   "Number of Trials argument is %1%, but must be >= 0 !", N, pol);
0110                return false;
0111            }
0112            return true;
0113         }
0114         template <class RealType, class Policy>
0115         inline bool check_success_fraction(const char* function, const RealType& p, RealType* result, const Policy& pol)
0116         {
0117            if((p < 0) || (p > 1) || !(boost::math::isfinite)(p))
0118            {
0119                *result = policies::raise_domain_error<RealType>(
0120                   function,
0121                   "Success fraction argument is %1%, but must be >= 0 and <= 1 !", p, pol);
0122                return false;
0123            }
0124            return true;
0125         }
0126         template <class RealType, class Policy>
0127         inline bool check_dist(const char* function, const RealType& N, const RealType& p, RealType* result, const Policy& pol)
0128         {
0129            return check_success_fraction(
0130               function, p, result, pol)
0131               && check_N(
0132                function, N, result, pol);
0133         }
0134         template <class RealType, class Policy>
0135         inline bool check_dist_and_k(const char* function, const RealType& N, const RealType& p, RealType k, RealType* result, const Policy& pol)
0136         {
0137            if(check_dist(function, N, p, result, pol) == false)
0138               return false;
0139            if((k < 0) || !(boost::math::isfinite)(k))
0140            {
0141                *result = policies::raise_domain_error<RealType>(
0142                   function,
0143                   "Number of Successes argument is %1%, but must be >= 0 !", k, pol);
0144                return false;
0145            }
0146            if(k > N)
0147            {
0148                *result = policies::raise_domain_error<RealType>(
0149                   function,
0150                   "Number of Successes argument is %1%, but must be <= Number of Trials !", k, pol);
0151                return false;
0152            }
0153            return true;
0154         }
0155         template <class RealType, class Policy>
0156         inline bool check_dist_and_prob(const char* function, const RealType& N, RealType p, RealType prob, RealType* result, const Policy& pol)
0157         {
0158            if((check_dist(function, N, p, result, pol) && detail::check_probability(function, prob, result, pol)) == false)
0159               return false;
0160            return true;
0161         }
0162 
0163          template <class T, class Policy>
0164          T inverse_binomial_cornish_fisher(T n, T sf, T p, T q, const Policy& pol)
0165          {
0166             BOOST_MATH_STD_USING
0167             // mean:
0168             T m = n * sf;
0169             // standard deviation:
0170             T sigma = sqrt(n * sf * (1 - sf));
0171             // skewness
0172             T sk = (1 - 2 * sf) / sigma;
0173             // kurtosis:
0174             // T k = (1 - 6 * sf * (1 - sf) ) / (n * sf * (1 - sf));
0175             // Get the inverse of a std normal distribution:
0176             T x = boost::math::erfc_inv(p > q ? 2 * q : 2 * p, pol) * constants::root_two<T>();
0177             // Set the sign:
0178             if(p < 0.5)
0179                x = -x;
0180             T x2 = x * x;
0181             // w is correction term due to skewness
0182             T w = x + sk * (x2 - 1) / 6;
0183             /*
0184             // Add on correction due to kurtosis.
0185             // Disabled for now, seems to make things worse?
0186             //
0187             if(n >= 10)
0188                w += k * x * (x2 - 3) / 24 + sk * sk * x * (2 * x2 - 5) / -36;
0189                */
0190             w = m + sigma * w;
0191             if(w < tools::min_value<T>())
0192                return sqrt(tools::min_value<T>());
0193             if(w > n)
0194                return n;
0195             return w;
0196          }
0197 
0198       template <class RealType, class Policy>
0199       RealType quantile_imp(const binomial_distribution<RealType, Policy>& dist, const RealType& p, const RealType& q, bool comp)
0200       { // Quantile or Percent Point Binomial function.
0201         // Return the number of expected successes k,
0202         // for a given probability p.
0203         //
0204         // Error checks:
0205         BOOST_MATH_STD_USING  // ADL of std names
0206         RealType result = 0;
0207         RealType trials = dist.trials();
0208         RealType success_fraction = dist.success_fraction();
0209         if(false == binomial_detail::check_dist_and_prob(
0210            "boost::math::quantile(binomial_distribution<%1%> const&, %1%)",
0211            trials,
0212            success_fraction,
0213            p,
0214            &result, Policy()))
0215         {
0216            return result;
0217         }
0218 
0219         // Special cases:
0220         //
0221         if(p == 0)
0222         {  // There may actually be no answer to this question,
0223            // since the probability of zero successes may be non-zero,
0224            // but zero is the best we can do:
0225            return 0;
0226         }
0227         if(p == 1 || success_fraction == 1)
0228         {  // Probability of n or fewer successes is always one,
0229            // so n is the most sensible answer here:
0230            return trials;
0231         }
0232         if (p <= pow(1 - success_fraction, trials))
0233         { // p <= pdf(dist, 0) == cdf(dist, 0)
0234           return 0; // So the only reasonable result is zero.
0235         } // And root finder would fail otherwise.
0236 
0237         // Solve for quantile numerically:
0238         //
0239         RealType guess = binomial_detail::inverse_binomial_cornish_fisher(trials, success_fraction, p, q, Policy());
0240         RealType factor = 8;
0241         if(trials > 100)
0242            factor = 1.01f; // guess is pretty accurate
0243         else if((trials > 10) && (trials - 1 > guess) && (guess > 3))
0244            factor = 1.15f; // less accurate but OK.
0245         else if(trials < 10)
0246         {
0247            // pretty inaccurate guess in this area:
0248            if(guess > trials / 64)
0249            {
0250               guess = trials / 4;
0251               factor = 2;
0252            }
0253            else
0254               guess = trials / 1024;
0255         }
0256         else
0257            factor = 2; // trials largish, but in far tails.
0258 
0259         typedef typename Policy::discrete_quantile_type discrete_quantile_type;
0260         std::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
0261         result = detail::inverse_discrete_quantile(
0262             dist,
0263             comp ? q : p,
0264             comp,
0265             guess,
0266             factor,
0267             RealType(1),
0268             discrete_quantile_type(),
0269             max_iter);
0270         return result;
0271       } // quantile
0272 
0273      }
0274 
0275     template <class RealType = double, class Policy = policies::policy<> >
0276     class binomial_distribution
0277     {
0278     public:
0279       typedef RealType value_type;
0280       typedef Policy policy_type;
0281 
0282       binomial_distribution(RealType n = 1, RealType p = 0.5) : m_n(n), m_p(p)
0283       { // Default n = 1 is the Bernoulli distribution
0284         // with equal probability of 'heads' or 'tails.
0285          RealType r;
0286          binomial_detail::check_dist(
0287             "boost::math::binomial_distribution<%1%>::binomial_distribution",
0288             m_n,
0289             m_p,
0290             &r, Policy());
0291       } // binomial_distribution constructor.
0292 
0293       RealType success_fraction() const
0294       { // Probability.
0295         return m_p;
0296       }
0297       RealType trials() const
0298       { // Total number of trials.
0299         return m_n;
0300       }
0301 
0302       enum interval_type{
0303          clopper_pearson_exact_interval,
0304          jeffreys_prior_interval
0305       };
0306 
0307       //
0308       // Estimation of the success fraction parameter.
0309       // The best estimate is actually simply successes/trials,
0310       // these functions are used
0311       // to obtain confidence intervals for the success fraction.
0312       //
0313       static RealType find_lower_bound_on_p(
0314          RealType trials,
0315          RealType successes,
0316          RealType probability,
0317          interval_type t = clopper_pearson_exact_interval)
0318       {
0319         static const char* function = "boost::math::binomial_distribution<%1%>::find_lower_bound_on_p";
0320         // Error checks:
0321         RealType result = 0;
0322         if(false == binomial_detail::check_dist_and_k(
0323            function, trials, RealType(0), successes, &result, Policy())
0324             &&
0325            binomial_detail::check_dist_and_prob(
0326            function, trials, RealType(0), probability, &result, Policy()))
0327         { return result; }
0328 
0329         if(successes == 0)
0330            return 0;
0331 
0332         // NOTE!!! The Clopper Pearson formula uses "successes" not
0333         // "successes+1" as usual to get the lower bound,
0334         // see http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
0335         return (t == clopper_pearson_exact_interval) ? ibeta_inv(successes, trials - successes + 1, probability, static_cast<RealType*>(nullptr), Policy())
0336            : ibeta_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(nullptr), Policy());
0337       }
0338       static RealType find_upper_bound_on_p(
0339          RealType trials,
0340          RealType successes,
0341          RealType probability,
0342          interval_type t = clopper_pearson_exact_interval)
0343       {
0344         static const char* function = "boost::math::binomial_distribution<%1%>::find_upper_bound_on_p";
0345         // Error checks:
0346         RealType result = 0;
0347         if(false == binomial_detail::check_dist_and_k(
0348            function, trials, RealType(0), successes, &result, Policy())
0349             &&
0350            binomial_detail::check_dist_and_prob(
0351            function, trials, RealType(0), probability, &result, Policy()))
0352         { return result; }
0353 
0354         if(trials == successes)
0355            return 1;
0356 
0357         return (t == clopper_pearson_exact_interval) ? ibetac_inv(successes + 1, trials - successes, probability, static_cast<RealType*>(nullptr), Policy())
0358            : ibetac_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(nullptr), Policy());
0359       }
0360       // Estimate number of trials parameter:
0361       //
0362       // "How many trials do I need to be P% sure of seeing k events?"
0363       //    or
0364       // "How many trials can I have to be P% sure of seeing fewer than k events?"
0365       //
0366       static RealType find_minimum_number_of_trials(
0367          RealType k,     // number of events
0368          RealType p,     // success fraction
0369          RealType alpha) // risk level
0370       {
0371         static const char* function = "boost::math::binomial_distribution<%1%>::find_minimum_number_of_trials";
0372         // Error checks:
0373         RealType result = 0;
0374         if(false == binomial_detail::check_dist_and_k(
0375            function, k, p, k, &result, Policy())
0376             &&
0377            binomial_detail::check_dist_and_prob(
0378            function, k, p, alpha, &result, Policy()))
0379         { return result; }
0380 
0381         result = ibetac_invb(k + 1, p, alpha, Policy());  // returns n - k
0382         return result + k;
0383       }
0384 
0385       static RealType find_maximum_number_of_trials(
0386          RealType k,     // number of events
0387          RealType p,     // success fraction
0388          RealType alpha) // risk level
0389       {
0390         static const char* function = "boost::math::binomial_distribution<%1%>::find_maximum_number_of_trials";
0391         // Error checks:
0392         RealType result = 0;
0393         if(false == binomial_detail::check_dist_and_k(
0394            function, k, p, k, &result, Policy())
0395             &&
0396            binomial_detail::check_dist_and_prob(
0397            function, k, p, alpha, &result, Policy()))
0398         { return result; }
0399 
0400         result = ibeta_invb(k + 1, p, alpha, Policy());  // returns n - k
0401         return result + k;
0402       }
0403 
0404     private:
0405         RealType m_n; // Not sure if this shouldn't be an int?
0406         RealType m_p; // success_fraction
0407       }; // template <class RealType, class Policy> class binomial_distribution
0408 
0409       typedef binomial_distribution<> binomial;
0410       // typedef binomial_distribution<double> binomial;
0411       // IS now included since no longer a name clash with function binomial.
0412       //typedef binomial_distribution<double> binomial; // Reserved name of type double.
0413 
0414       #ifdef __cpp_deduction_guides
0415       template <class RealType>
0416       binomial_distribution(RealType)->binomial_distribution<typename boost::math::tools::promote_args<RealType>::type>;
0417       template <class RealType>
0418       binomial_distribution(RealType,RealType)->binomial_distribution<typename boost::math::tools::promote_args<RealType>::type>;
0419       #endif
0420 
0421       template <class RealType, class Policy>
0422       const std::pair<RealType, RealType> range(const binomial_distribution<RealType, Policy>& dist)
0423       { // Range of permissible values for random variable k.
0424         using boost::math::tools::max_value;
0425         return std::pair<RealType, RealType>(static_cast<RealType>(0), dist.trials());
0426       }
0427 
0428       template <class RealType, class Policy>
0429       const std::pair<RealType, RealType> support(const binomial_distribution<RealType, Policy>& dist)
0430       { // Range of supported values for random variable k.
0431         // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
0432         return std::pair<RealType, RealType>(static_cast<RealType>(0),  dist.trials());
0433       }
0434 
0435       template <class RealType, class Policy>
0436       inline RealType mean(const binomial_distribution<RealType, Policy>& dist)
0437       { // Mean of Binomial distribution = np.
0438         return  dist.trials() * dist.success_fraction();
0439       } // mean
0440 
0441       template <class RealType, class Policy>
0442       inline RealType variance(const binomial_distribution<RealType, Policy>& dist)
0443       { // Variance of Binomial distribution = np(1-p).
0444         return  dist.trials() * dist.success_fraction() * (1 - dist.success_fraction());
0445       } // variance
0446 
0447       template <class RealType, class Policy>
0448       RealType pdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
0449       { // Probability Density/Mass Function.
0450         BOOST_FPU_EXCEPTION_GUARD
0451 
0452         BOOST_MATH_STD_USING // for ADL of std functions
0453 
0454         RealType n = dist.trials();
0455 
0456         // Error check:
0457         RealType result = 0; // initialization silences some compiler warnings
0458         if(false == binomial_detail::check_dist_and_k(
0459            "boost::math::pdf(binomial_distribution<%1%> const&, %1%)",
0460            n,
0461            dist.success_fraction(),
0462            k,
0463            &result, Policy()))
0464         {
0465            return result;
0466         }
0467 
0468         // Special cases of success_fraction, regardless of k successes and regardless of n trials.
0469         if (dist.success_fraction() == 0)
0470         {  // probability of zero successes is 1:
0471            return static_cast<RealType>(k == 0 ? 1 : 0);
0472         }
0473         if (dist.success_fraction() == 1)
0474         {  // probability of n successes is 1:
0475            return static_cast<RealType>(k == n ? 1 : 0);
0476         }
0477         // k argument may be integral, signed, or unsigned, or floating point.
0478         // If necessary, it has already been promoted from an integral type.
0479         if (n == 0)
0480         {
0481           return 1; // Probability = 1 = certainty.
0482         }
0483         if (k == n)
0484         { // binomial coeffic (n n) = 1,
0485           // n ^ 0 = 1
0486           return pow(dist.success_fraction(), k);  // * pow((1 - dist.success_fraction()), (n - k)) = 1
0487         }
0488 
0489         // Probability of getting exactly k successes
0490         // if C(n, k) is the binomial coefficient then:
0491         //
0492         // f(k; n,p) = C(n, k) * p^k * (1-p)^(n-k)
0493         //           = (n!/(k!(n-k)!)) * p^k * (1-p)^(n-k)
0494         //           = (tgamma(n+1) / (tgamma(k+1)*tgamma(n-k+1))) * p^k * (1-p)^(n-k)
0495         //           = p^k (1-p)^(n-k) / (beta(k+1, n-k+1) * (n+1))
0496         //           = ibeta_derivative(k+1, n-k+1, p) / (n+1)
0497         //
0498         using boost::math::ibeta_derivative; // a, b, x
0499         return ibeta_derivative(k+1, n-k+1, dist.success_fraction(), Policy()) / (n+1);
0500 
0501       } // pdf
0502 
0503       template <class RealType, class Policy>
0504       inline RealType cdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
0505       { // Cumulative Distribution Function Binomial.
0506         // The random variate k is the number of successes in n trials.
0507         // k argument may be integral, signed, or unsigned, or floating point.
0508         // If necessary, it has already been promoted from an integral type.
0509 
0510         // Returns the sum of the terms 0 through k of the Binomial Probability Density/Mass:
0511         //
0512         //   i=k
0513         //   --  ( n )   i      n-i
0514         //   >   |   |  p  (1-p)
0515         //   --  ( i )
0516         //   i=0
0517 
0518         // The terms are not summed directly instead
0519         // the incomplete beta integral is employed,
0520         // according to the formula:
0521         // P = I[1-p]( n-k, k+1).
0522         //   = 1 - I[p](k + 1, n - k)
0523 
0524         BOOST_MATH_STD_USING // for ADL of std functions
0525 
0526         RealType n = dist.trials();
0527         RealType p = dist.success_fraction();
0528 
0529         // Error check:
0530         RealType result = 0;
0531         if(false == binomial_detail::check_dist_and_k(
0532            "boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
0533            n,
0534            p,
0535            k,
0536            &result, Policy()))
0537         {
0538            return result;
0539         }
0540         if (k == n)
0541         {
0542           return 1;
0543         }
0544 
0545         // Special cases, regardless of k.
0546         if (p == 0)
0547         {  // This need explanation:
0548            // the pdf is zero for all cases except when k == 0.
0549            // For zero p the probability of zero successes is one.
0550            // Therefore the cdf is always 1:
0551            // the probability of k or *fewer* successes is always 1
0552            // if there are never any successes!
0553            return 1;
0554         }
0555         if (p == 1)
0556         { // This is correct but needs explanation:
0557           // when k = 1
0558           // all the cdf and pdf values are zero *except* when k == n,
0559           // and that case has been handled above already.
0560           return 0;
0561         }
0562         //
0563         // P = I[1-p](n - k, k + 1)
0564         //   = 1 - I[p](k + 1, n - k)
0565         // Use of ibetac here prevents cancellation errors in calculating
0566         // 1-p if p is very small, perhaps smaller than machine epsilon.
0567         //
0568         // Note that we do not use a finite sum here, since the incomplete
0569         // beta uses a finite sum internally for integer arguments, so
0570         // we'll just let it take care of the necessary logic.
0571         //
0572         return ibetac(k + 1, n - k, p, Policy());
0573       } // binomial cdf
0574 
0575       template <class RealType, class Policy>
0576       inline RealType cdf(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
0577       { // Complemented Cumulative Distribution Function Binomial.
0578         // The random variate k is the number of successes in n trials.
0579         // k argument may be integral, signed, or unsigned, or floating point.
0580         // If necessary, it has already been promoted from an integral type.
0581 
0582         // Returns the sum of the terms k+1 through n of the Binomial Probability Density/Mass:
0583         //
0584         //   i=n
0585         //   --  ( n )   i      n-i
0586         //   >   |   |  p  (1-p)
0587         //   --  ( i )
0588         //   i=k+1
0589 
0590         // The terms are not summed directly instead
0591         // the incomplete beta integral is employed,
0592         // according to the formula:
0593         // Q = 1 -I[1-p]( n-k, k+1).
0594         //   = I[p](k + 1, n - k)
0595 
0596         BOOST_MATH_STD_USING // for ADL of std functions
0597 
0598         RealType const& k = c.param;
0599         binomial_distribution<RealType, Policy> const& dist = c.dist;
0600         RealType n = dist.trials();
0601         RealType p = dist.success_fraction();
0602 
0603         // Error checks:
0604         RealType result = 0;
0605         if(false == binomial_detail::check_dist_and_k(
0606            "boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
0607            n,
0608            p,
0609            k,
0610            &result, Policy()))
0611         {
0612            return result;
0613         }
0614 
0615         if (k == n)
0616         { // Probability of greater than n successes is necessarily zero:
0617           return 0;
0618         }
0619 
0620         // Special cases, regardless of k.
0621         if (p == 0)
0622         {
0623            // This need explanation: the pdf is zero for all
0624            // cases except when k == 0.  For zero p the probability
0625            // of zero successes is one.  Therefore the cdf is always
0626            // 1: the probability of *more than* k successes is always 0
0627            // if there are never any successes!
0628            return 0;
0629         }
0630         if (p == 1)
0631         {
0632           // This needs explanation, when p = 1
0633           // we always have n successes, so the probability
0634           // of more than k successes is 1 as long as k < n.
0635           // The k == n case has already been handled above.
0636           return 1;
0637         }
0638         //
0639         // Calculate cdf binomial using the incomplete beta function.
0640         // Q = 1 -I[1-p](n - k, k + 1)
0641         //   = I[p](k + 1, n - k)
0642         // Use of ibeta here prevents cancellation errors in calculating
0643         // 1-p if p is very small, perhaps smaller than machine epsilon.
0644         //
0645         // Note that we do not use a finite sum here, since the incomplete
0646         // beta uses a finite sum internally for integer arguments, so
0647         // we'll just let it take care of the necessary logic.
0648         //
0649         return ibeta(k + 1, n - k, p, Policy());
0650       } // binomial cdf
0651 
0652       template <class RealType, class Policy>
0653       inline RealType quantile(const binomial_distribution<RealType, Policy>& dist, const RealType& p)
0654       {
0655          return binomial_detail::quantile_imp(dist, p, RealType(1-p), false);
0656       } // quantile
0657 
0658       template <class RealType, class Policy>
0659       RealType quantile(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
0660       {
0661          return binomial_detail::quantile_imp(c.dist, RealType(1-c.param), c.param, true);
0662       } // quantile
0663 
0664       template <class RealType, class Policy>
0665       inline RealType mode(const binomial_distribution<RealType, Policy>& dist)
0666       {
0667          BOOST_MATH_STD_USING // ADL of std functions.
0668          RealType p = dist.success_fraction();
0669          RealType n = dist.trials();
0670          return floor(p * (n + 1));
0671       }
0672 
0673       template <class RealType, class Policy>
0674       inline RealType median(const binomial_distribution<RealType, Policy>& dist)
0675       { // Bounds for the median of the negative binomial distribution
0676         // VAN DE VEN R. ; WEBER N. C. ;
0677         // Univ. Sydney, school mathematics statistics, Sydney N.S.W. 2006, AUSTRALIE
0678         // Metrika  (Metrika)  ISSN 0026-1335   CODEN MTRKA8
0679         // 1993, vol. 40, no3-4, pp. 185-189 (4 ref.)
0680 
0681         // Bounds for median and 50 percentage point of binomial and negative binomial distribution
0682         // Metrika, ISSN   0026-1335 (Print) 1435-926X (Online)
0683         // Volume 41, Number 1 / December, 1994, DOI   10.1007/BF01895303
0684          BOOST_MATH_STD_USING // ADL of std functions.
0685          RealType p = dist.success_fraction();
0686          RealType n = dist.trials();
0687          // Wikipedia says one of floor(np) -1, floor (np), floor(np) +1
0688          return floor(p * n); // Chose the middle value.
0689       }
0690 
0691       template <class RealType, class Policy>
0692       inline RealType skewness(const binomial_distribution<RealType, Policy>& dist)
0693       {
0694          BOOST_MATH_STD_USING // ADL of std functions.
0695          RealType p = dist.success_fraction();
0696          RealType n = dist.trials();
0697          return (1 - 2 * p) / sqrt(n * p * (1 - p));
0698       }
0699 
0700       template <class RealType, class Policy>
0701       inline RealType kurtosis(const binomial_distribution<RealType, Policy>& dist)
0702       {
0703          RealType p = dist.success_fraction();
0704          RealType n = dist.trials();
0705          return 3 - 6 / n + 1 / (n * p * (1 - p));
0706       }
0707 
0708       template <class RealType, class Policy>
0709       inline RealType kurtosis_excess(const binomial_distribution<RealType, Policy>& dist)
0710       {
0711          RealType p = dist.success_fraction();
0712          RealType q = 1 - p;
0713          RealType n = dist.trials();
0714          return (1 - 6 * p * q) / (n * p * q);
0715       }
0716 
0717     } // namespace math
0718   } // namespace boost
0719 
0720 // This include must be at the end, *after* the accessors
0721 // for this distribution have been defined, in order to
0722 // keep compilers that support two-phase lookup happy.
0723 #include <boost/math/distributions/detail/derived_accessors.hpp>
0724 
0725 #endif // BOOST_MATH_SPECIAL_BINOMIAL_HPP
0726 
0727