1 // boost\math\distributions\geometric.hpp
3 // Copyright John Maddock 2010.
4 // Copyright Paul A. Bristow 2010.
6 // Use, modification and distribution are subject to the
7 // Boost Software License, Version 1.0.
8 // (See accompanying file LICENSE_1_0.txt
9 // or copy at http://www.boost.org/LICENSE_1_0.txt)
11 // geometric distribution is a discrete probability distribution.
12 // It expresses the probability distribution of the number (k) of
13 // events, occurrences, failures or arrivals before the first success.
14 // supported on the set {0, 1, 2, 3...}
16 // Note that the set includes zero (unlike some definitions that start at one).
18 // The random variate k is the number of events, occurrences or arrivals.
19 // k argument may be integral, signed, or unsigned, or floating point.
20 // If necessary, it has already been promoted from an integral type.
22 // Note that the geometric distribution
23 // (like others including the binomial, geometric & Bernoulli)
24 // is strictly defined as a discrete function:
25 // only integral values of k are envisaged.
26 // However because the method of calculation uses a continuous gamma function,
27 // it is convenient to treat it as if a continuous function,
28 // and permit non-integral values of k.
29 // To enforce the strict mathematical model, users should use floor or ceil functions
30 // on k outside this function to ensure that k is integral.
32 // See http://en.wikipedia.org/wiki/geometric_distribution
33 // http://documents.wolfram.com/v5/Add-onsLinks/StandardPackages/Statistics/DiscreteDistributions.html
34 // http://mathworld.wolfram.com/GeometricDistribution.html
36 #ifndef BOOST_MATH_SPECIAL_GEOMETRIC_HPP
37 #define BOOST_MATH_SPECIAL_GEOMETRIC_HPP
39 #include <boost/math/distributions/fwd.hpp>
40 #include <boost/math/special_functions/beta.hpp> // for ibeta(a, b, x) == Ix(a, b).
41 #include <boost/math/distributions/complement.hpp> // complement.
42 #include <boost/math/distributions/detail/common_error_handling.hpp> // error checks domain_error & logic_error.
43 #include <boost/math/special_functions/fpclassify.hpp> // isnan.
44 #include <boost/math/tools/roots.hpp> // for root finding.
45 #include <boost/math/distributions/detail/inv_discrete_quantile.hpp>
47 #include <limits> // using std::numeric_limits;
50 #if defined (BOOST_MSVC)
51 # pragma warning(push)
52 // This believed not now necessary, so commented out.
53 //# pragma warning(disable: 4702) // unreachable code.
54 // in domain_error_imp in error_handling.
61 namespace geometric_detail
63 // Common error checking routines for geometric distribution function:
64 template <class RealType, class Policy>
65 inline bool check_success_fraction(const char* function, const RealType& p, RealType* result, const Policy& pol)
67 if( !(boost::math::isfinite)(p) || (p < 0) || (p > 1) )
69 *result = policies::raise_domain_error<RealType>(
71 "Success fraction argument is %1%, but must be >= 0 and <= 1 !", p, pol);
77 template <class RealType, class Policy>
78 inline bool check_dist(const char* function, const RealType& p, RealType* result, const Policy& pol)
80 return check_success_fraction(function, p, result, pol);
83 template <class RealType, class Policy>
84 inline bool check_dist_and_k(const char* function, const RealType& p, RealType k, RealType* result, const Policy& pol)
86 if(check_dist(function, p, result, pol) == false)
90 if( !(boost::math::isfinite)(k) || (k < 0) )
91 { // Check k failures.
92 *result = policies::raise_domain_error<RealType>(
94 "Number of failures argument is %1%, but must be >= 0 !", k, pol);
100 template <class RealType, class Policy>
101 inline bool check_dist_and_prob(const char* function, RealType p, RealType prob, RealType* result, const Policy& pol)
103 if((check_dist(function, p, result, pol) && detail::check_probability(function, prob, result, pol)) == false)
108 } // check_dist_and_prob
109 } // namespace geometric_detail
111 template <class RealType = double, class Policy = policies::policy<> >
112 class geometric_distribution
115 typedef RealType value_type;
116 typedef Policy policy_type;
118 geometric_distribution(RealType p) : m_p(p)
119 { // Constructor stores success_fraction p.
121 geometric_detail::check_dist(
122 "geometric_distribution<%1%>::geometric_distribution",
123 m_p, // Check success_fraction 0 <= p <= 1.
125 } // geometric_distribution constructor.
127 // Private data getter class member functions.
128 RealType success_fraction() const
129 { // Probability of success as fraction in range 0 to 1.
132 RealType successes() const
133 { // Total number of successes r = 1 (for compatibility with negative binomial?).
137 // Parameter estimation.
138 // (These are copies of negative_binomial distribution with successes = 1).
139 static RealType find_lower_bound_on_p(
141 RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.
143 static const char* function = "boost::math::geometric<%1%>::find_lower_bound_on_p";
144 RealType result = 0; // of error checks.
145 RealType successes = 1;
146 RealType failures = trials - successes;
147 if(false == detail::check_probability(function, alpha, &result, Policy())
148 && geometric_detail::check_dist_and_k(
149 function, RealType(0), failures, &result, Policy()))
153 // Use complement ibeta_inv function for lower bound.
154 // This is adapted from the corresponding binomial formula
155 // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
156 // This is a Clopper-Pearson interval, and may be overly conservative,
157 // see also "A Simple Improved Inferential Method for Some
158 // Discrete Distributions" Yong CAI and K. KRISHNAMOORTHY
159 // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf
161 return ibeta_inv(successes, failures + 1, alpha, static_cast<RealType*>(nullptr), Policy());
162 } // find_lower_bound_on_p
164 static RealType find_upper_bound_on_p(
166 RealType alpha) // alpha 0.05 equivalent to 95% for one-sided test.
168 static const char* function = "boost::math::geometric<%1%>::find_upper_bound_on_p";
169 RealType result = 0; // of error checks.
170 RealType successes = 1;
171 RealType failures = trials - successes;
172 if(false == geometric_detail::check_dist_and_k(
173 function, RealType(0), failures, &result, Policy())
174 && detail::check_probability(function, alpha, &result, Policy()))
181 }// Use complement ibetac_inv function for upper bound.
182 // Note adjusted failures value: *not* failures+1 as usual.
183 // This is adapted from the corresponding binomial formula
184 // here: http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
185 // This is a Clopper-Pearson interval, and may be overly conservative,
186 // see also "A Simple Improved Inferential Method for Some
187 // Discrete Distributions" Yong CAI and K. Krishnamoorthy
188 // http://www.ucs.louisiana.edu/~kxk4695/Discrete_new.pdf
190 return ibetac_inv(successes, failures, alpha, static_cast<RealType*>(nullptr), Policy());
191 } // find_upper_bound_on_p
193 // Estimate number of trials :
194 // "How many trials do I need to be P% sure of seeing k or fewer failures?"
196 static RealType find_minimum_number_of_trials(
197 RealType k, // number of failures (k >= 0).
198 RealType p, // success fraction 0 <= p <= 1.
199 RealType alpha) // risk level threshold 0 <= alpha <= 1.
201 static const char* function = "boost::math::geometric<%1%>::find_minimum_number_of_trials";
204 if(false == geometric_detail::check_dist_and_k(
205 function, p, k, &result, Policy())
206 && detail::check_probability(function, alpha, &result, Policy()))
210 result = ibeta_inva(k + 1, p, alpha, Policy()); // returns n - k
212 } // RealType find_number_of_failures
214 static RealType find_maximum_number_of_trials(
215 RealType k, // number of failures (k >= 0).
216 RealType p, // success fraction 0 <= p <= 1.
217 RealType alpha) // risk level threshold 0 <= alpha <= 1.
219 static const char* function = "boost::math::geometric<%1%>::find_maximum_number_of_trials";
222 if(false == geometric_detail::check_dist_and_k(
223 function, p, k, &result, Policy())
224 && detail::check_probability(function, alpha, &result, Policy()))
228 result = ibetac_inva(k + 1, p, alpha, Policy()); // returns n - k
230 } // RealType find_number_of_trials complemented
233 //RealType m_r; // successes fixed at unity.
234 RealType m_p; // success_fraction
235 }; // template <class RealType, class Policy> class geometric_distribution
237 typedef geometric_distribution<double> geometric; // Reserved name of type double.
239 #ifdef __cpp_deduction_guides
240 template <class RealType>
241 geometric_distribution(RealType)->geometric_distribution<typename boost::math::tools::promote_args<RealType>::type>;
244 template <class RealType, class Policy>
245 inline const std::pair<RealType, RealType> range(const geometric_distribution<RealType, Policy>& /* dist */)
246 { // Range of permissible values for random variable k.
247 using boost::math::tools::max_value;
248 return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // max_integer?
251 template <class RealType, class Policy>
252 inline const std::pair<RealType, RealType> support(const geometric_distribution<RealType, Policy>& /* dist */)
253 { // Range of supported values for random variable k.
254 // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
255 using boost::math::tools::max_value;
256 return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // max_integer?
259 template <class RealType, class Policy>
260 inline RealType mean(const geometric_distribution<RealType, Policy>& dist)
261 { // Mean of geometric distribution = (1-p)/p.
262 return (1 - dist.success_fraction() ) / dist.success_fraction();
265 // median implemented via quantile(half) in derived accessors.
267 template <class RealType, class Policy>
268 inline RealType mode(const geometric_distribution<RealType, Policy>&)
269 { // Mode of geometric distribution = zero.
270 BOOST_MATH_STD_USING // ADL of std functions.
274 template <class RealType, class Policy>
275 inline RealType variance(const geometric_distribution<RealType, Policy>& dist)
276 { // Variance of Binomial distribution = (1-p) / p^2.
277 return (1 - dist.success_fraction())
278 / (dist.success_fraction() * dist.success_fraction());
281 template <class RealType, class Policy>
282 inline RealType skewness(const geometric_distribution<RealType, Policy>& dist)
283 { // skewness of geometric distribution = 2-p / (sqrt(r(1-p))
284 BOOST_MATH_STD_USING // ADL of std functions.
285 RealType p = dist.success_fraction();
286 return (2 - p) / sqrt(1 - p);
289 template <class RealType, class Policy>
290 inline RealType kurtosis(const geometric_distribution<RealType, Policy>& dist)
291 { // kurtosis of geometric distribution
292 // http://en.wikipedia.org/wiki/geometric is kurtosis_excess so add 3
293 RealType p = dist.success_fraction();
294 return 3 + (p*p - 6*p + 6) / (1 - p);
297 template <class RealType, class Policy>
298 inline RealType kurtosis_excess(const geometric_distribution<RealType, Policy>& dist)
299 { // kurtosis excess of geometric distribution
300 // http://mathworld.wolfram.com/Kurtosis.html table of kurtosis_excess
301 RealType p = dist.success_fraction();
302 return (p*p - 6*p + 6) / (1 - p);
305 // RealType standard_deviation(const geometric_distribution<RealType, Policy>& dist)
306 // standard_deviation provided by derived accessors.
307 // RealType hazard(const geometric_distribution<RealType, Policy>& dist)
308 // hazard of geometric distribution provided by derived accessors.
309 // RealType chf(const geometric_distribution<RealType, Policy>& dist)
310 // chf of geometric distribution provided by derived accessors.
312 template <class RealType, class Policy>
313 inline RealType pdf(const geometric_distribution<RealType, Policy>& dist, const RealType& k)
314 { // Probability Density/Mass Function.
315 BOOST_FPU_EXCEPTION_GUARD
316 BOOST_MATH_STD_USING // For ADL of math functions.
317 static const char* function = "boost::math::pdf(const geometric_distribution<%1%>&, %1%)";
319 RealType p = dist.success_fraction();
321 if(false == geometric_detail::check_dist_and_k(
331 return p; // success_fraction
333 RealType q = 1 - p; // Inaccurate for small p?
334 // So try to avoid inaccuracy for large or small p.
335 // but has little effect > last significant bit.
336 //cout << "p * pow(q, k) " << result << endl; // seems best whatever p
337 //cout << "exp(p * k * log1p(-p)) " << p * exp(k * log1p(-p)) << endl;
340 // result = p * pow(q, k);
344 // result = p * exp(k * log1p(-p));
346 result = p * pow(q, k);
350 template <class RealType, class Policy>
351 inline RealType cdf(const geometric_distribution<RealType, Policy>& dist, const RealType& k)
352 { // Cumulative Distribution Function of geometric.
353 static const char* function = "boost::math::cdf(const geometric_distribution<%1%>&, %1%)";
355 // k argument may be integral, signed, or unsigned, or floating point.
356 // If necessary, it has already been promoted from an integral type.
357 RealType p = dist.success_fraction();
360 if(false == geometric_detail::check_dist_and_k(
370 return p; // success_fraction
372 //RealType q = 1 - p; // Bad for small p
373 //RealType probability = 1 - std::pow(q, k+1);
375 RealType z = boost::math::log1p(-p, Policy()) * (k + 1);
376 RealType probability = -boost::math::expm1(z, Policy());
379 } // cdf Cumulative Distribution Function geometric.
381 template <class RealType, class Policy>
382 inline RealType cdf(const complemented2_type<geometric_distribution<RealType, Policy>, RealType>& c)
383 { // Complemented Cumulative Distribution Function geometric.
385 static const char* function = "boost::math::cdf(const geometric_distribution<%1%>&, %1%)";
386 // k argument may be integral, signed, or unsigned, or floating point.
387 // If necessary, it has already been promoted from an integral type.
388 RealType const& k = c.param;
389 geometric_distribution<RealType, Policy> const& dist = c.dist;
390 RealType p = dist.success_fraction();
393 if(false == geometric_detail::check_dist_and_k(
401 RealType z = boost::math::log1p(-p, Policy()) * (k+1);
402 RealType probability = exp(z);
404 } // cdf Complemented Cumulative Distribution Function geometric.
406 template <class RealType, class Policy>
407 inline RealType quantile(const geometric_distribution<RealType, Policy>& dist, const RealType& x)
408 { // Quantile, percentile/100 or Percent Point geometric function.
409 // Return the number of expected failures k for a given probability p.
411 // Inverse cumulative Distribution Function or Quantile (percentile / 100) of geometric Probability.
412 // k argument may be integral, signed, or unsigned, or floating point.
414 static const char* function = "boost::math::quantile(const geometric_distribution<%1%>&, %1%)";
415 BOOST_MATH_STD_USING // ADL of std functions.
417 RealType success_fraction = dist.success_fraction();
420 if(false == geometric_detail::check_dist_and_prob
421 (function, success_fraction, x, &result, Policy()))
428 { // Would need +infinity failures for total confidence.
429 result = policies::raise_overflow_error<RealType>(
431 "Probability argument is 1, which implies infinite failures !", Policy());
433 // usually means return +std::numeric_limits<RealType>::infinity();
434 // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR
437 { // No failures are expected if P = 0.
438 return 0; // Total trials will be just dist.successes.
440 // if (P <= pow(dist.success_fraction(), 1))
441 if (x <= success_fraction)
442 { // p <= pdf(dist, 0) == cdf(dist, 0)
450 // log(1-x) /log(1-success_fraction) -1; but use log1p in case success_fraction is small
451 result = boost::math::log1p(-x, Policy()) / boost::math::log1p(-success_fraction, Policy()) - 1;
452 // Subtract a few epsilons here too?
453 // to make sure it doesn't slip over, so ceil would be one too many.
455 } // RealType quantile(const geometric_distribution dist, p)
457 template <class RealType, class Policy>
458 inline RealType quantile(const complemented2_type<geometric_distribution<RealType, Policy>, RealType>& c)
459 { // Quantile or Percent Point Binomial function.
460 // Return the number of expected failures k for a given
461 // complement of the probability Q = 1 - P.
462 static const char* function = "boost::math::quantile(const geometric_distribution<%1%>&, %1%)";
465 RealType x = c.param;
466 const geometric_distribution<RealType, Policy>& dist = c.dist;
467 RealType success_fraction = dist.success_fraction();
469 if(false == geometric_detail::check_dist_and_prob(
480 { // There may actually be no answer to this question,
481 // since the probability of zero failures may be non-zero,
482 return 0; // but zero is the best we can do:
484 if (-x <= boost::math::powm1(dist.success_fraction(), dist.successes(), Policy()))
485 { // q <= cdf(complement(dist, 0)) == pdf(dist, 0)
489 { // Probability 1 - Q == 1 so infinite failures to achieve certainty.
490 // Would need +infinity failures for total confidence.
491 result = policies::raise_overflow_error<RealType>(
493 "Probability argument complement is 0, which implies infinite failures !", Policy());
495 // usually means return +std::numeric_limits<RealType>::infinity();
496 // unless #define BOOST_MATH_THROW_ON_OVERFLOW_ERROR
498 // log(x) /log(1-success_fraction) -1; but use log1p in case success_fraction is small
499 result = log(x) / boost::math::log1p(-success_fraction, Policy()) - 1;
502 } // quantile complement
507 // This include must be at the end, *after* the accessors
508 // for this distribution have been defined, in order to
509 // keep compilers that support two-phase lookup happy.
510 #include <boost/math/distributions/detail/derived_accessors.hpp>
512 #if defined (BOOST_MSVC)
513 # pragma warning(pop)
516 #endif // BOOST_MATH_SPECIAL_GEOMETRIC_HPP