Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-30 09:45:23

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         return 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       } // quantile
0271 
0272      }
0273 
0274     template <class RealType = double, class Policy = policies::policy<> >
0275     class binomial_distribution
0276     {
0277     public:
0278       typedef RealType value_type;
0279       typedef Policy policy_type;
0280 
0281       binomial_distribution(RealType n = 1, RealType p = 0.5) : m_n(n), m_p(p)
0282       { // Default n = 1 is the Bernoulli distribution
0283         // with equal probability of 'heads' or 'tails.
0284          RealType r;
0285          binomial_detail::check_dist(
0286             "boost::math::binomial_distribution<%1%>::binomial_distribution",
0287             m_n,
0288             m_p,
0289             &r, Policy());
0290       } // binomial_distribution constructor.
0291 
0292       RealType success_fraction() const
0293       { // Probability.
0294         return m_p;
0295       }
0296       RealType trials() const
0297       { // Total number of trials.
0298         return m_n;
0299       }
0300 
0301       enum interval_type{
0302          clopper_pearson_exact_interval,
0303          jeffreys_prior_interval
0304       };
0305 
0306       //
0307       // Estimation of the success fraction parameter.
0308       // The best estimate is actually simply successes/trials,
0309       // these functions are used
0310       // to obtain confidence intervals for the success fraction.
0311       //
0312       static RealType find_lower_bound_on_p(
0313          RealType trials,
0314          RealType successes,
0315          RealType probability,
0316          interval_type t = clopper_pearson_exact_interval)
0317       {
0318         static const char* function = "boost::math::binomial_distribution<%1%>::find_lower_bound_on_p";
0319         // Error checks:
0320         RealType result = 0;
0321         if(false == binomial_detail::check_dist_and_k(
0322            function, trials, RealType(0), successes, &result, Policy())
0323             &&
0324            binomial_detail::check_dist_and_prob(
0325            function, trials, RealType(0), probability, &result, Policy()))
0326         { return result; }
0327 
0328         if(successes == 0)
0329            return 0;
0330 
0331         // NOTE!!! The Clopper Pearson formula uses "successes" not
0332         // "successes+1" as usual to get the lower bound,
0333         // see http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
0334         return (t == clopper_pearson_exact_interval) ? ibeta_inv(successes, trials - successes + 1, probability, static_cast<RealType*>(nullptr), Policy())
0335            : ibeta_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(nullptr), Policy());
0336       }
0337       static RealType find_upper_bound_on_p(
0338          RealType trials,
0339          RealType successes,
0340          RealType probability,
0341          interval_type t = clopper_pearson_exact_interval)
0342       {
0343         static const char* function = "boost::math::binomial_distribution<%1%>::find_upper_bound_on_p";
0344         // Error checks:
0345         RealType result = 0;
0346         if(false == binomial_detail::check_dist_and_k(
0347            function, trials, RealType(0), successes, &result, Policy())
0348             &&
0349            binomial_detail::check_dist_and_prob(
0350            function, trials, RealType(0), probability, &result, Policy()))
0351         { return result; }
0352 
0353         if(trials == successes)
0354            return 1;
0355 
0356         return (t == clopper_pearson_exact_interval) ? ibetac_inv(successes + 1, trials - successes, probability, static_cast<RealType*>(nullptr), Policy())
0357            : ibetac_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(nullptr), Policy());
0358       }
0359       // Estimate number of trials parameter:
0360       //
0361       // "How many trials do I need to be P% sure of seeing k events?"
0362       //    or
0363       // "How many trials can I have to be P% sure of seeing fewer than k events?"
0364       //
0365       static RealType find_minimum_number_of_trials(
0366          RealType k,     // number of events
0367          RealType p,     // success fraction
0368          RealType alpha) // risk level
0369       {
0370         static const char* function = "boost::math::binomial_distribution<%1%>::find_minimum_number_of_trials";
0371         // Error checks:
0372         RealType result = 0;
0373         if(false == binomial_detail::check_dist_and_k(
0374            function, k, p, k, &result, Policy())
0375             &&
0376            binomial_detail::check_dist_and_prob(
0377            function, k, p, alpha, &result, Policy()))
0378         { return result; }
0379 
0380         result = ibetac_invb(k + 1, p, alpha, Policy());  // returns n - k
0381         return result + k;
0382       }
0383 
0384       static RealType find_maximum_number_of_trials(
0385          RealType k,     // number of events
0386          RealType p,     // success fraction
0387          RealType alpha) // risk level
0388       {
0389         static const char* function = "boost::math::binomial_distribution<%1%>::find_maximum_number_of_trials";
0390         // Error checks:
0391         RealType result = 0;
0392         if(false == binomial_detail::check_dist_and_k(
0393            function, k, p, k, &result, Policy())
0394             &&
0395            binomial_detail::check_dist_and_prob(
0396            function, k, p, alpha, &result, Policy()))
0397         { return result; }
0398 
0399         result = ibeta_invb(k + 1, p, alpha, Policy());  // returns n - k
0400         return result + k;
0401       }
0402 
0403     private:
0404         RealType m_n; // Not sure if this shouldn't be an int?
0405         RealType m_p; // success_fraction
0406       }; // template <class RealType, class Policy> class binomial_distribution
0407 
0408       typedef binomial_distribution<> binomial;
0409       // typedef binomial_distribution<double> binomial;
0410       // IS now included since no longer a name clash with function binomial.
0411       //typedef binomial_distribution<double> binomial; // Reserved name of type double.
0412 
0413       #ifdef __cpp_deduction_guides
0414       template <class RealType>
0415       binomial_distribution(RealType)->binomial_distribution<typename boost::math::tools::promote_args<RealType>::type>;
0416       template <class RealType>
0417       binomial_distribution(RealType,RealType)->binomial_distribution<typename boost::math::tools::promote_args<RealType>::type>;
0418       #endif
0419 
0420       template <class RealType, class Policy>
0421       const std::pair<RealType, RealType> range(const binomial_distribution<RealType, Policy>& dist)
0422       { // Range of permissible values for random variable k.
0423         using boost::math::tools::max_value;
0424         return std::pair<RealType, RealType>(static_cast<RealType>(0), dist.trials());
0425       }
0426 
0427       template <class RealType, class Policy>
0428       const std::pair<RealType, RealType> support(const binomial_distribution<RealType, Policy>& dist)
0429       { // Range of supported values for random variable k.
0430         // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
0431         return std::pair<RealType, RealType>(static_cast<RealType>(0),  dist.trials());
0432       }
0433 
0434       template <class RealType, class Policy>
0435       inline RealType mean(const binomial_distribution<RealType, Policy>& dist)
0436       { // Mean of Binomial distribution = np.
0437         return  dist.trials() * dist.success_fraction();
0438       } // mean
0439 
0440       template <class RealType, class Policy>
0441       inline RealType variance(const binomial_distribution<RealType, Policy>& dist)
0442       { // Variance of Binomial distribution = np(1-p).
0443         return  dist.trials() * dist.success_fraction() * (1 - dist.success_fraction());
0444       } // variance
0445 
0446       template <class RealType, class Policy>
0447       RealType pdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
0448       { // Probability Density/Mass Function.
0449         BOOST_FPU_EXCEPTION_GUARD
0450 
0451         BOOST_MATH_STD_USING // for ADL of std functions
0452 
0453         RealType n = dist.trials();
0454 
0455         // Error check:
0456         RealType result = 0; // initialization silences some compiler warnings
0457         if(false == binomial_detail::check_dist_and_k(
0458            "boost::math::pdf(binomial_distribution<%1%> const&, %1%)",
0459            n,
0460            dist.success_fraction(),
0461            k,
0462            &result, Policy()))
0463         {
0464            return result;
0465         }
0466 
0467         // Special cases of success_fraction, regardless of k successes and regardless of n trials.
0468         if (dist.success_fraction() == 0)
0469         {  // probability of zero successes is 1:
0470            return static_cast<RealType>(k == 0 ? 1 : 0);
0471         }
0472         if (dist.success_fraction() == 1)
0473         {  // probability of n successes is 1:
0474            return static_cast<RealType>(k == n ? 1 : 0);
0475         }
0476         // k argument may be integral, signed, or unsigned, or floating point.
0477         // If necessary, it has already been promoted from an integral type.
0478         if (n == 0)
0479         {
0480           return 1; // Probability = 1 = certainty.
0481         }
0482         if (k == n)
0483         { // binomial coeffic (n n) = 1,
0484           // n ^ 0 = 1
0485           return pow(dist.success_fraction(), k);  // * pow((1 - dist.success_fraction()), (n - k)) = 1
0486         }
0487 
0488         // Probability of getting exactly k successes
0489         // if C(n, k) is the binomial coefficient then:
0490         //
0491         // f(k; n,p) = C(n, k) * p^k * (1-p)^(n-k)
0492         //           = (n!/(k!(n-k)!)) * p^k * (1-p)^(n-k)
0493         //           = (tgamma(n+1) / (tgamma(k+1)*tgamma(n-k+1))) * p^k * (1-p)^(n-k)
0494         //           = p^k (1-p)^(n-k) / (beta(k+1, n-k+1) * (n+1))
0495         //           = ibeta_derivative(k+1, n-k+1, p) / (n+1)
0496         //
0497         using boost::math::ibeta_derivative; // a, b, x
0498         return ibeta_derivative(k+1, n-k+1, dist.success_fraction(), Policy()) / (n+1);
0499 
0500       } // pdf
0501 
0502       template <class RealType, class Policy>
0503       inline RealType cdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
0504       { // Cumulative Distribution Function Binomial.
0505         // The random variate k is the number of successes in n trials.
0506         // k argument may be integral, signed, or unsigned, or floating point.
0507         // If necessary, it has already been promoted from an integral type.
0508 
0509         // Returns the sum of the terms 0 through k of the Binomial Probability Density/Mass:
0510         //
0511         //   i=k
0512         //   --  ( n )   i      n-i
0513         //   >   |   |  p  (1-p)
0514         //   --  ( i )
0515         //   i=0
0516 
0517         // The terms are not summed directly instead
0518         // the incomplete beta integral is employed,
0519         // according to the formula:
0520         // P = I[1-p]( n-k, k+1).
0521         //   = 1 - I[p](k + 1, n - k)
0522 
0523         BOOST_MATH_STD_USING // for ADL of std functions
0524 
0525         RealType n = dist.trials();
0526         RealType p = dist.success_fraction();
0527 
0528         // Error check:
0529         RealType result = 0;
0530         if(false == binomial_detail::check_dist_and_k(
0531            "boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
0532            n,
0533            p,
0534            k,
0535            &result, Policy()))
0536         {
0537            return result;
0538         }
0539         if (k == n)
0540         {
0541           return 1;
0542         }
0543 
0544         // Special cases, regardless of k.
0545         if (p == 0)
0546         {  // This need explanation:
0547            // the pdf is zero for all cases except when k == 0.
0548            // For zero p the probability of zero successes is one.
0549            // Therefore the cdf is always 1:
0550            // the probability of k or *fewer* successes is always 1
0551            // if there are never any successes!
0552            return 1;
0553         }
0554         if (p == 1)
0555         { // This is correct but needs explanation:
0556           // when k = 1
0557           // all the cdf and pdf values are zero *except* when k == n,
0558           // and that case has been handled above already.
0559           return 0;
0560         }
0561         //
0562         // P = I[1-p](n - k, k + 1)
0563         //   = 1 - I[p](k + 1, n - k)
0564         // Use of ibetac here prevents cancellation errors in calculating
0565         // 1-p if p is very small, perhaps smaller than machine epsilon.
0566         //
0567         // Note that we do not use a finite sum here, since the incomplete
0568         // beta uses a finite sum internally for integer arguments, so
0569         // we'll just let it take care of the necessary logic.
0570         //
0571         return ibetac(k + 1, n - k, p, Policy());
0572       } // binomial cdf
0573 
0574       template <class RealType, class Policy>
0575       inline RealType cdf(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
0576       { // Complemented Cumulative Distribution Function Binomial.
0577         // The random variate k is the number of successes in n trials.
0578         // k argument may be integral, signed, or unsigned, or floating point.
0579         // If necessary, it has already been promoted from an integral type.
0580 
0581         // Returns the sum of the terms k+1 through n of the Binomial Probability Density/Mass:
0582         //
0583         //   i=n
0584         //   --  ( n )   i      n-i
0585         //   >   |   |  p  (1-p)
0586         //   --  ( i )
0587         //   i=k+1
0588 
0589         // The terms are not summed directly instead
0590         // the incomplete beta integral is employed,
0591         // according to the formula:
0592         // Q = 1 -I[1-p]( n-k, k+1).
0593         //   = I[p](k + 1, n - k)
0594 
0595         BOOST_MATH_STD_USING // for ADL of std functions
0596 
0597         RealType const& k = c.param;
0598         binomial_distribution<RealType, Policy> const& dist = c.dist;
0599         RealType n = dist.trials();
0600         RealType p = dist.success_fraction();
0601 
0602         // Error checks:
0603         RealType result = 0;
0604         if(false == binomial_detail::check_dist_and_k(
0605            "boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
0606            n,
0607            p,
0608            k,
0609            &result, Policy()))
0610         {
0611            return result;
0612         }
0613 
0614         if (k == n)
0615         { // Probability of greater than n successes is necessarily zero:
0616           return 0;
0617         }
0618 
0619         // Special cases, regardless of k.
0620         if (p == 0)
0621         {
0622            // This need explanation: the pdf is zero for all
0623            // cases except when k == 0.  For zero p the probability
0624            // of zero successes is one.  Therefore the cdf is always
0625            // 1: the probability of *more than* k successes is always 0
0626            // if there are never any successes!
0627            return 0;
0628         }
0629         if (p == 1)
0630         {
0631           // This needs explanation, when p = 1
0632           // we always have n successes, so the probability
0633           // of more than k successes is 1 as long as k < n.
0634           // The k == n case has already been handled above.
0635           return 1;
0636         }
0637         //
0638         // Calculate cdf binomial using the incomplete beta function.
0639         // Q = 1 -I[1-p](n - k, k + 1)
0640         //   = I[p](k + 1, n - k)
0641         // Use of ibeta here prevents cancellation errors in calculating
0642         // 1-p if p is very small, perhaps smaller than machine epsilon.
0643         //
0644         // Note that we do not use a finite sum here, since the incomplete
0645         // beta uses a finite sum internally for integer arguments, so
0646         // we'll just let it take care of the necessary logic.
0647         //
0648         return ibeta(k + 1, n - k, p, Policy());
0649       } // binomial cdf
0650 
0651       template <class RealType, class Policy>
0652       inline RealType quantile(const binomial_distribution<RealType, Policy>& dist, const RealType& p)
0653       {
0654          return binomial_detail::quantile_imp(dist, p, RealType(1-p), false);
0655       } // quantile
0656 
0657       template <class RealType, class Policy>
0658       RealType quantile(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
0659       {
0660          return binomial_detail::quantile_imp(c.dist, RealType(1-c.param), c.param, true);
0661       } // quantile
0662 
0663       template <class RealType, class Policy>
0664       inline RealType mode(const binomial_distribution<RealType, Policy>& dist)
0665       {
0666          BOOST_MATH_STD_USING // ADL of std functions.
0667          RealType p = dist.success_fraction();
0668          RealType n = dist.trials();
0669          return floor(p * (n + 1));
0670       }
0671 
0672       template <class RealType, class Policy>
0673       inline RealType median(const binomial_distribution<RealType, Policy>& dist)
0674       { // Bounds for the median of the negative binomial distribution
0675         // VAN DE VEN R. ; WEBER N. C. ;
0676         // Univ. Sydney, school mathematics statistics, Sydney N.S.W. 2006, AUSTRALIE
0677         // Metrika  (Metrika)  ISSN 0026-1335   CODEN MTRKA8
0678         // 1993, vol. 40, no3-4, pp. 185-189 (4 ref.)
0679 
0680         // Bounds for median and 50 percentage point of binomial and negative binomial distribution
0681         // Metrika, ISSN   0026-1335 (Print) 1435-926X (Online)
0682         // Volume 41, Number 1 / December, 1994, DOI   10.1007/BF01895303
0683          BOOST_MATH_STD_USING // ADL of std functions.
0684          RealType p = dist.success_fraction();
0685          RealType n = dist.trials();
0686          // Wikipedia says one of floor(np) -1, floor (np), floor(np) +1
0687          return floor(p * n); // Chose the middle value.
0688       }
0689 
0690       template <class RealType, class Policy>
0691       inline RealType skewness(const binomial_distribution<RealType, Policy>& dist)
0692       {
0693          BOOST_MATH_STD_USING // ADL of std functions.
0694          RealType p = dist.success_fraction();
0695          RealType n = dist.trials();
0696          return (1 - 2 * p) / sqrt(n * p * (1 - p));
0697       }
0698 
0699       template <class RealType, class Policy>
0700       inline RealType kurtosis(const binomial_distribution<RealType, Policy>& dist)
0701       {
0702          RealType p = dist.success_fraction();
0703          RealType n = dist.trials();
0704          return 3 - 6 / n + 1 / (n * p * (1 - p));
0705       }
0706 
0707       template <class RealType, class Policy>
0708       inline RealType kurtosis_excess(const binomial_distribution<RealType, Policy>& dist)
0709       {
0710          RealType p = dist.success_fraction();
0711          RealType q = 1 - p;
0712          RealType n = dist.trials();
0713          return (1 - 6 * p * q) / (n * p * q);
0714       }
0715 
0716     } // namespace math
0717   } // namespace boost
0718 
0719 // This include must be at the end, *after* the accessors
0720 // for this distribution have been defined, in order to
0721 // keep compilers that support two-phase lookup happy.
0722 #include <boost/math/distributions/detail/derived_accessors.hpp>
0723 
0724 #endif // BOOST_MATH_SPECIAL_BINOMIAL_HPP
0725 
0726