Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-15 08:39:34

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