From e0737c56c1e384e05064a0c6e1ac46979371041b Mon Sep 17 00:00:00 2001 From: Christoph Berg Date: Wed, 19 Dec 2018 22:58:32 +0100 Subject: New upstream version 2.0.0+repack --- .../html/math_toolkit/stat_tut/dist_params.html | 100 ++ .../doc/html/math_toolkit/stat_tut/overview.html | 59 + .../stat_tut/overview/complements.html | 200 +++ .../math_toolkit/stat_tut/overview/generic.html | 254 ++++ .../math_toolkit/stat_tut/overview/headers.html | 78 ++ .../math_toolkit/stat_tut/overview/objects.html | 134 ++ .../math_toolkit/stat_tut/overview/parameters.html | 73 ++ .../math_toolkit/stat_tut/overview/summary.html | 75 ++ .../doc/html/math_toolkit/stat_tut/variates.html | 76 ++ .../math/doc/html/math_toolkit/stat_tut/weg.html | 129 ++ .../html/math_toolkit/stat_tut/weg/binom_eg.html | 61 + .../stat_tut/weg/binom_eg/binom_conf.html | 241 ++++ .../stat_tut/weg/binom_eg/binom_size_eg.html | 160 +++ .../weg/binom_eg/binomial_coinflip_example.html | 274 +++++ .../weg/binom_eg/binomial_quiz_example.html | 458 +++++++ .../html/math_toolkit/stat_tut/weg/c_sharp.html | 58 + .../doc/html/math_toolkit/stat_tut/weg/cs_eg.html | 55 + .../stat_tut/weg/cs_eg/chi_sq_intervals.html | 236 ++++ .../stat_tut/weg/cs_eg/chi_sq_size.html | 182 +++ .../stat_tut/weg/cs_eg/chi_sq_test.html | 297 +++++ .../stat_tut/weg/dist_construct_eg.html | 333 +++++ .../html/math_toolkit/stat_tut/weg/error_eg.html | 206 ++++ .../doc/html/math_toolkit/stat_tut/weg/f_eg.html | 329 +++++ .../html/math_toolkit/stat_tut/weg/find_eg.html | 55 + .../stat_tut/weg/find_eg/find_location_eg.html | 190 +++ .../stat_tut/weg/find_eg/find_mean_and_sd_eg.html | 455 +++++++ .../stat_tut/weg/find_eg/find_scale_eg.html | 209 ++++ .../math_toolkit/stat_tut/weg/geometric_eg.html | 422 +++++++ .../stat_tut/weg/inverse_chi_squared_eg.html | 360 ++++++ .../math_toolkit/stat_tut/weg/nag_library.html | 116 ++ .../html/math_toolkit/stat_tut/weg/nccs_eg.html | 53 + .../stat_tut/weg/nccs_eg/nccs_power_eg.html | 1287 ++++++++++++++++++++ .../math_toolkit/stat_tut/weg/neg_binom_eg.html | 62 + .../stat_tut/weg/neg_binom_eg/neg_binom_conf.html | 221 ++++ .../weg/neg_binom_eg/neg_binom_size_eg.html | 207 ++++ .../neg_binom_eg/negative_binomial_example1.html | 507 ++++++++ .../neg_binom_eg/negative_binomial_example2.html | 136 +++ .../math_toolkit/stat_tut/weg/normal_example.html | 53 + .../stat_tut/weg/normal_example/normal_misc.html | 518 ++++++++ .../doc/html/math_toolkit/stat_tut/weg/st_eg.html | 60 + .../math_toolkit/stat_tut/weg/st_eg/paired_st.html | 81 ++ .../stat_tut/weg/st_eg/tut_mean_intervals.html | 267 ++++ .../stat_tut/weg/st_eg/tut_mean_size.html | 179 +++ .../stat_tut/weg/st_eg/tut_mean_test.html | 334 +++++ .../stat_tut/weg/st_eg/two_sample_students_t.html | 359 ++++++ 45 files changed, 10199 insertions(+) create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/dist_params.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/overview.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/overview/complements.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/overview/generic.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/overview/headers.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/overview/objects.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/overview/parameters.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/overview/summary.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/variates.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binom_conf.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binom_size_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binomial_coinflip_example.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binomial_quiz_example.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/c_sharp.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_intervals.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_size.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_test.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/dist_construct_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/error_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/f_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_location_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_mean_and_sd_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_scale_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/geometric_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/inverse_chi_squared_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nag_library.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nccs_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nccs_eg/nccs_power_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/neg_binom_conf.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/neg_binom_size_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/negative_binomial_example1.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/negative_binomial_example2.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/normal_example.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/normal_example/normal_misc.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/paired_st.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_intervals.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_size.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_test.html create mode 100644 boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/two_sample_students_t.html (limited to 'boost/libs/math/doc/html/math_toolkit/stat_tut') diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/dist_params.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/dist_params.html new file mode 100644 index 00000000..c9e0fe23 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/dist_params.html @@ -0,0 +1,100 @@ + + + +Discrete Probability Distributions + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Note that the discrete + distributions, including the binomial, negative binomial, Poisson + & Bernoulli, are all mathematically defined as discrete functions: only + integral values of the random + variate are envisaged and the functions are only defined at these + integral values. However because the method of calculation often uses continuous + functions, it is convenient to treat them as if they were continuous functions, + and permit non-integral values of their parameters. +

+

+ To enforce a strict mathematical model, users may use floor or ceil functions + on the random variate, + prior to calling the distribution function, to enforce integral values. +

+

+ For similar reasons, in continuous distributions, parameters like degrees + of freedom that might appear to be integral, are treated as real values (and + are promoted from integer to floating-point if necessary). In this case however, + that there are a small number of situations where non-integral degrees of + freedom do have a genuine meaning. +

+

+ Generally speaking there is no loss of performance from allowing real-values + parameters: the underlying special functions contain optimizations for integer-valued + arguments when applicable. +

+
+ + + + + +
[Caution]Caution
+

+ The quantile function of a discrete distribution will by default return + an integer result that has been rounded outwards. + That is to say lower quantiles (where the probability is less than 0.5) + are rounded downward, and upper quantiles (where the probability is greater + than 0.5) are rounded upwards. This behaviour ensures that if an X% quantile + is requested, then at least the requested coverage + will be present in the central region, and no more than + the requested coverage will be present in the tails. +

+

+ This behaviour can be changed so that the quantile functions are rounded + differently, or even return a real-valued result using Policies. + It is strongly recommended that you read the tutorial Understanding + Quantiles of Discrete Distributions before using the quantile function + on a discrete distribution. The reference + docs describe how to change the rounding policy for these distributions. +

+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/overview.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview.html new file mode 100644 index 00000000..31489cfd --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview.html @@ -0,0 +1,59 @@ + + + +Overview of Distributions + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ + +
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/complements.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/complements.html new file mode 100644 index 00000000..defcbc96 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/complements.html @@ -0,0 +1,200 @@ + + + +Complements are supported too - and when to use them + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Often you don't want the value of the CDF, but its complement, which is + to say 1-p rather than p. + It is tempting to calculate the CDF and subtract it from 1, but if p + is very close to 1 then cancellation + error will cause you to lose accuracy, perhaps totally. +

+

+ See below "Why and when + to use complements?" +

+

+ In this library, whenever you want to receive a complement, just wrap all + the function arguments in a call to complement(...), for example: +

+
students_t dist(5);
+cout << "CDF at t = 1 is " << cdf(dist, 1.0) << endl;
+cout << "Complement of CDF at t = 1 is " << cdf(complement(dist, 1.0)) << endl;
+
+

+ But wait, now that we have a complement, we have to be able to use it as + well. Any function that accepts a probability as an argument can also accept + a complement by wrapping all of its arguments in a call to complement(...), + for example: +

+
students_t dist(5);
+
+for(double i = 10; i < 1e10; i *= 10)
+{
+   // Calculate the quantile for a 1 in i chance:
+   double t = quantile(complement(dist, 1/i));
+   // Print it out:
+   cout << "Quantile of students-t with 5 degrees of freedom\n"
+           "for a 1 in " << i << " chance is " << t << endl;
+}
+
+
+ + + + + +
[Tip]Tip
+

+ Critical values are just quantiles +

+

+ Some texts talk about quantiles, or percentiles or fractiles, others + about critical values, the basic rule is: +

+

+ Lower critical values are the same as the quantile. +

+

+ Upper critical values are the same as the quantile + from the complement of the probability. +

+

+ For example, suppose we have a Bernoulli process, giving rise to a binomial + distribution with success ratio 0.1 and 100 trials in total. The lower + critical value for a probability of 0.05 is given by: +

+

+ quantile(binomial(100, 0.1), 0.05) +

+

+ and the upper critical value is given by: +

+

+ quantile(complement(binomial(100, 0.1), 0.05)) +

+

+ which return 4.82 and 14.63 respectively. +

+
+
+ + + + + +
[Tip]Tip
+

+ Why bother with complements anyway? +

+

+ It's very tempting to dispense with complements, and simply subtract + the probability from 1 when required. However, consider what happens + when the probability is very close to 1: let's say the probability expressed + at float precision is 0.999999940f, + then 1 - + 0.999999940f = + 5.96046448e-008, but the result + is actually accurate to just one single bit: the + only bit that didn't cancel out! +

+

+ Or to look at this another way: consider that we want the risk of falsely + rejecting the null-hypothesis in the Student's t test to be 1 in 1 billion, + for a sample size of 10,000. This gives a probability of 1 - 10-9, which + is exactly 1 when calculated at float precision. In this case calculating + the quantile from the complement neatly solves the problem, so for example: +

+

+ quantile(complement(students_t(10000), 1e-9)) +

+

+ returns the expected t-statistic 6.00336, + where as: +

+

+ quantile(students_t(10000), 1-1e-9f) +

+

+ raises an overflow error, since it is the same as: +

+

+ quantile(students_t(10000), 1) +

+

+ Which has no finite result. +

+

+ With all distributions, even for more reasonable probability (unless + the value of p can be represented exactly in the floating-point type) + the loss of accuracy quickly becomes significant if you simply calculate + probability from 1 - p (because it will be mostly garbage digits for + p ~ 1). +

+

+ So always avoid, for example, using a probability near to unity like + 0.99999 +

+

+ quantile(my_distribution, + 0.99999) +

+

+ and instead use +

+

+ quantile(complement(my_distribution, + 0.00001)) +

+

+ since 1 - 0.99999 is not exactly equal to 0.00001 when using floating-point + arithmetic. +

+

+ This assumes that the 0.00001 value is either a constant, or can be computed + by some manner other than subtracting 0.99999 from 1. +

+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/generic.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/generic.html new file mode 100644 index 00000000..839388f9 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/generic.html @@ -0,0 +1,254 @@ + + + +Generic operations common to all distributions are non-member functions + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Want to calculate the PDF (Probability Density Function) of a distribution? + No problem, just use: +

+
pdf(my_dist, x);  // Returns PDF (density) at point x of distribution my_dist.
+
+

+ Or how about the CDF (Cumulative Distribution Function): +

+
cdf(my_dist, x);  // Returns CDF (integral from -infinity to point x)
+                  // of distribution my_dist.
+
+

+ And quantiles are just the same: +

+
quantile(my_dist, p);  // Returns the value of the random variable x
+                       // such that cdf(my_dist, x) == p.
+
+

+ If you're wondering why these aren't member functions, it's to make the + library more easily extensible: if you want to add additional generic operations + - let's say the n'th moment - then all you have to + do is add the appropriate non-member functions, overloaded for each implemented + distribution type. +

+
+ + + + + +
[Tip]Tip
+

+ Random numbers that approximate Quantiles of Distributions +

+

+ If you want random numbers that are distributed in a specific way, for + example in a uniform, normal or triangular, see Boost.Random. +

+

+ Whilst in principal there's nothing to prevent you from using the quantile + function to convert a uniformly distributed random number to another + distribution, in practice there are much more efficient algorithms available + that are specific to random number generation. +

+
+

+ For example, the binomial distribution has two parameters: n (the number + of trials) and p (the probability of success on any one trial). +

+

+ The binomial_distribution + constructor therefore has two parameters: +

+

+ binomial_distribution(RealType n, RealType + p); +

+

+ For this distribution the random + variate is k: the number of successes observed. The probability + density/mass function (pdf) is therefore written as f(k; n, p). +

+
+ + + + + +
[Note]Note
+

+ Random Variates and Distribution Parameters +

+

+ The concept of a random + variable is closely linked to the term random + variate: a random variate is a particular value (outcome) of + a random variable. and distribution + parameters are conventionally distinguished (for example in Wikipedia + and Wolfram MathWorld) by placing a semi-colon or vertical bar) after + the random + variable (whose value you 'choose'), to separate the variate + from the parameter(s) that defines the shape of the distribution.
+ For example, the binomial distribution probability distribution function + (PDF) is written as f(k| n, p) = Pr(K = k|n, p) + = probability of observing k successes out of n trials. K is the random variable, + k is the random + variate, the parameters are n (trials) and p (probability). +

+
+
+ + + + + +
[Note]Note

+ By convention, random + variate are lower case, usually k is integral, x if real, and + random variable + are upper case, K if integral, X if real. But this implementation treats + all as floating point values RealType, + so if you really want an integral result, you must round: see note on + Discrete Probability Distributions below for details. +

+

+ As noted above the non-member function pdf + has one parameter for the distribution object, and a second for the random + variate. So taking our binomial distribution example, we would write: +

+

+ pdf(binomial_distribution<RealType>(n, p), k); +

+

+ The ranges of random + variate values that are permitted and are supported can be tested + by using two functions range + and support. +

+

+ The distribution (effectively the random + variate) is said to be 'supported' over a range that is "the smallest + closed set whose complement has probability zero". MathWorld + uses the word 'defined' for this range. Non-mathematicians might say it + means the 'interesting' smallest range of random variate x that has the + cdf going from zero to unity. Outside are uninteresting zones where the + pdf is zero, and the cdf zero or unity. +

+

+ For most distributions, with probability distribution functions one might + describe as 'well-behaved', we have decided that it is most useful for + the supported range to exclude random + variate values like exact zero if the end point is + discontinuous. For example, the Weibull (scale 1, shape 1) distribution + smoothly heads for unity as the random variate x declines towards zero. + But at x = zero, the value of the pdf is suddenly exactly zero, by definition. + If you are plotting the PDF, or otherwise calculating, zero is not the + most useful value for the lower limit of supported, as we discovered. So + for this, and similar distributions, we have decided it is most numerically + useful to use the closest value to zero, min_value, for the limit of the + supported range. (The range + remains from zero, so you will still get pdf(weibull, 0) + == 0). + (Exponential and gamma distributions have similarly discontinuous functions). +

+

+ Mathematically, the functions may make sense with an (+ or -) infinite + value, but except for a few special cases (in the Normal and Cauchy distributions) + this implementation limits random variates to finite values from the max to min + for the RealType. (See + Handling + of Floating-Point Infinity for rationale). +

+
+ + + + + +
[Note]Note
+

+ Discrete Probability Distributions +

+

+ Note that the discrete + distributions, including the binomial, negative binomial, Poisson + & Bernoulli, are all mathematically defined as discrete functions: + that is to say the functions cdf + and pdf are only defined + for integral values of the random variate. +

+

+ However, because the method of calculation often uses continuous functions + it is convenient to treat them as if they were continuous functions, + and permit non-integral values of their parameters. +

+

+ Users wanting to enforce a strict mathematical model may use floor or ceil + functions on the random variate prior to calling the distribution function. +

+

+ The quantile functions for these distributions are hard to specify in + a manner that will satisfy everyone all of the time. The default behaviour + is to return an integer result, that has been rounded outwards: + that is to say, lower quantiles - where the probablity is less than 0.5 + are rounded down, while upper quantiles - where the probability is greater + than 0.5 - are rounded up. This behaviour ensures that if an X% quantile + is requested, then at least the requested coverage + will be present in the central region, and no more than + the requested coverage will be present in the tails. +

+

+ This behaviour can be changed so that the quantile functions are rounded + differently, or return a real-valued result using Policies. + It is strongly recommended that you read the tutorial Understanding + Quantiles of Discrete Distributions before using the quantile + function on a discrete distribtion. The reference + docs describe how to change the rounding policy for these distributions. +

+

+ For similar reasons continuous distributions with parameters like "degrees + of freedom" that might appear to be integral, are treated as real + values (and are promoted from integer to floating-point if necessary). + In this case however, there are a small number of situations where non-integral + degrees of freedom do have a genuine meaning. +

+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/headers.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/headers.html new file mode 100644 index 00000000..c0f4395e --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/headers.html @@ -0,0 +1,78 @@ + + + +Headers and Namespaces + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ All the code in this library is inside namespace boost::math. +

+

+ In order to use a distribution my_distribution you + will need to include either the header <boost/math/my_distribution.hpp> + or the "include all the distributions" header: <boost/math/distributions.hpp>. +

+

+ For example, to use the Students-t distribution include either <boost/math/students_t.hpp> + or <boost/math/distributions.hpp> +

+

+ You also need to bring distribution names into scope, perhaps with a using namespace + boost::math; + declaration, +

+

+ or specific using declarations + like using boost::math::normal; (recommended). +

+
+ + + + + +
[Caution]Caution

+ Some math function names are also used in namespace std so including + <random> could cause ambiguity! +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/objects.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/objects.html new file mode 100644 index 00000000..f0d3ed83 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/objects.html @@ -0,0 +1,134 @@ + + + +Distributions are Objects + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Each kind of distribution in this library is a class type - an object. +

+

+ Policies provide fine-grained control of + the behaviour of these classes, allowing the user to customise behaviour + such as how errors are handled, or how the quantiles of discrete distribtions + behave. +

+
+ + + + + +
[Tip]Tip

+ If you are familiar with statistics libraries using functions, and 'Distributions + as Objects' seem alien, see the + comparison to other statistics libraries. +

+

+ Making distributions class types does two things: +

+
    +
  • + It encapsulates the kind of distribution in the C++ type system; so, + for example, Students-t distributions are always a different C++ type + from Chi-Squared distributions. +
  • +
  • + The distribution objects store any parameters associated with the distribution: + for example, the Students-t distribution has a degrees of + freedom parameter that controls the shape of the distribution. + This degrees of freedom parameter has to be provided + to the Students-t object when it is constructed. +
  • +
+

+ Although the distribution classes in this library are templates, there + are typedefs on type double that mostly take the usual + name of the distribution (except where there is a clash with a function + of the same name: beta and gamma, in which case using the default template + arguments - RealType = + double - is nearly as convenient). + Probably 95% of uses are covered by these typedefs: +

+
// using namespace boost::math; // Avoid potential ambiguity with names in std <random>
+// Safer to declare specific functions with using statement(s):
+
+using boost::math::beta_distribution;
+using boost::math::binomial_distribution;
+using boost::math::students_t;
+
+// Construct a students_t distribution with 4 degrees of freedom:
+students_t d1(4);
+
+// Construct a double-precision beta distribution
+// with parameters a = 10, b = 20
+beta_distribution<> d2(10, 20); // Note: _distribution<> suffix !
+
+

+ If you need to use the distributions with a type other than double, then you can instantiate the template + directly: the names of the templates are the same as the double typedef but with _distribution + appended, for example: Students + t Distribution or Binomial + Distribution: +

+
// Construct a students_t distribution, of float type,
+// with 4 degrees of freedom:
+students_t_distribution<float> d3(4);
+
+// Construct a binomial distribution, of long double type,
+// with probability of success 0.3
+// and 20 trials in total:
+binomial_distribution<long double> d4(20, 0.3);
+
+

+ The parameters passed to the distributions can be accessed via getter member + functions: +

+
d1.degrees_of_freedom();  // returns 4.0
+
+

+ This is all well and good, but not very useful so far. What we often want + is to be able to calculate the cumulative distribution functions + and quantiles etc for these distributions. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/parameters.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/parameters.html new file mode 100644 index 00000000..03e7fa8d --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/parameters.html @@ -0,0 +1,73 @@ + + + +Parameters can be calculated + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Sometimes it's the parameters that define the distribution that you need + to find. Suppose, for example, you have conducted a Students-t test for + equal means and the result is borderline. Maybe your two samples differ + from each other, or maybe they don't; based on the result of the test you + can't be sure. A legitimate question to ask then is "How many more + measurements would I have to take before I would get an X% probability + that the difference is real?" Parameter finders can answer questions + like this, and are necessarily different for each distribution. They are + implemented as static member functions of the distributions, for example: +

+
students_t::find_degrees_of_freedom(
+   1.3,        // difference from true mean to detect
+   0.05,       // maximum risk of falsely rejecting the null-hypothesis.
+   0.1,        // maximum risk of falsely failing to reject the null-hypothesis.
+   0.13);      // sample standard deviation
+
+

+ Returns the number of degrees of freedom required to obtain a 95% probability + that the observed differences in means is not down to chance alone. In + the case that a borderline Students-t test result was previously obtained, + this can be used to estimate how large the sample size would have to become + before the observed difference was considered significant. It assumes, + of course, that the sample mean and standard deviation are invariant with + sample size. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/summary.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/summary.html new file mode 100644 index 00000000..cc2a0844 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/overview/summary.html @@ -0,0 +1,75 @@ + + + +Summary + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +
    +
  • + Distributions are objects, which are constructed from whatever parameters + the distribution may have. +
  • +
  • + Member functions allow you to retrieve the parameters of a distribution. +
  • +
  • + Generic non-member functions provide access to the properties that + are common to all the distributions (PDF, CDF, quantile etc). +
  • +
  • + Complements of probabilities are calculated by wrapping the function's + arguments in a call to complement(...). +
  • +
  • + Functions that accept a probability can accept a complement of the + probability as well, by wrapping the function's arguments in a call + to complement(...). +
  • +
  • + Static member functions allow the parameters of a distribution to be + found from other information. +
  • +
+

+ Now that you have the basics, the next section looks at some worked examples. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/variates.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/variates.html new file mode 100644 index 00000000..324e14e9 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/variates.html @@ -0,0 +1,76 @@ + + + +Random Variates and Distribution Parameters + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Random variates + and distribution parameters + are conventionally distinguished (for example in Wikipedia and Wolfram MathWorld + by placing a semi-colon after the random + variate (whose value you 'choose'), to separate the variate from + the parameter(s) that defines the shape of the distribution. +

+

+ For example, the binomial distribution has two parameters: n (the number + of trials) and p (the probability of success on one trial). It also has the + random variate + k: the number of successes observed. This means the + probability density/mass function (pdf) is written as f(k; n, p). +

+

+ Translating this into code the binomial_distribution + constructor therefore has two parameters: +

+
binomial_distribution(RealType n, RealType p);
+
+

+ While the function pdf has + one argument specifying the distribution type (which includes its parameters, + if any), and a second argument for the random + variate. So taking our binomial distribution example, we would write: +

+
pdf(binomial_distribution<RealType>(n, p), k);
+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg.html new file mode 100644 index 00000000..d6d82879 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg.html @@ -0,0 +1,129 @@ + + + +Worked Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +
+
Distribution + Construction Examples
+
Student's t Distribution + Examples
+
+
Calculating + confidence intervals on the mean with the Students-t distribution
+
Testing + a sample mean for difference from a "true" mean
+
Estimating + how large a sample size would have to become in order to give a significant + Students-t test result with a single sample test
+
Comparing + the means of two samples with the Students-t test
+
Comparing + two paired samples with the Student's t distribution
+
+
Chi Squared Distribution + Examples
+
+
Confidence + Intervals on the Standard Deviation
+
Chi-Square + Test for the Standard Deviation
+
Estimating + the Required Sample Sizes for a Chi-Square Test for the Standard Deviation
+
+
F Distribution Examples
+
Binomial Distribution + Examples
+
+
Binomial + Coin-Flipping Example
+
Binomial + Quiz Example
+
Calculating + Confidence Limits on the Frequency of Occurrence for a Binomial Distribution
+
Estimating + Sample Sizes for a Binomial Distribution.
+
+
Geometric Distribution + Examples
+
Negative Binomial + Distribution Examples
+
+
Calculating + Confidence Limits on the Frequency of Occurrence for the Negative Binomial + Distribution
+
Estimating + Sample Sizes for the Negative Binomial.
+
Negative + Binomial Sales Quota Example.
+
Negative + Binomial Table Printing Example.
+
+
Normal Distribution + Examples
+
Some + Miscellaneous Examples of the Normal (Gaussian) Distribution
+
Inverse + Chi-Squared Distribution Bayes Example
+
Non Central Chi + Squared Example
+
Tables + of the power function of the chi2 test.
+
Error Handling + Example
+
Find Location and + Scale Examples
+
+
Find + Location (Mean) Example
+
Find + Scale (Standard Deviation) Example
+
Find + mean and standard deviation example
+
+
Comparison with + C, R, FORTRAN-style Free Functions
+
Using the Distributions + from Within C#
+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg.html new file mode 100644 index 00000000..6e055cd0 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg.html @@ -0,0 +1,61 @@ + + + +Binomial Distribution Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ + +

+ See also the reference documentation for the Binomial + Distribution. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binom_conf.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binom_conf.html new file mode 100644 index 00000000..03374cc0 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binom_conf.html @@ -0,0 +1,241 @@ + + + +Calculating Confidence Limits on the Frequency of Occurrence for a Binomial Distribution + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Imagine you have a process that follows a binomial distribution: for + each trial conducted, an event either occurs or does it does not, referred + to as "successes" and "failures". If, by experiment, + you want to measure the frequency with which successes occur, the best + estimate is given simply by k / N, + for k successes out of N trials. + However our confidence in that estimate will be shaped by how many trials + were conducted, and how many successes were observed. The static member + functions binomial_distribution<>::find_lower_bound_on_p + and binomial_distribution<>::find_upper_bound_on_p + allow you to calculate the confidence intervals for your estimate of + the occurrence frequency. +

+

+ The sample program binomial_confidence_limits.cpp + illustrates their use. It begins by defining a procedure that will print + a table of confidence limits for various degrees of certainty: +

+
#include <iostream>
+#include <iomanip>
+#include <boost/math/distributions/binomial.hpp>
+
+void confidence_limits_on_frequency(unsigned trials, unsigned successes)
+{
+   //
+   // trials = Total number of trials.
+   // successes = Total number of observed successes.
+   //
+   // Calculate confidence limits for an observed
+   // frequency of occurrence that follows a binomial
+   // distribution.
+   //
+   using namespace std;
+   using namespace boost::math;
+
+   // Print out general info:
+   cout <<
+      "___________________________________________\n"
+      "2-Sided Confidence Limits For Success Ratio\n"
+      "___________________________________________\n\n";
+   cout << setprecision(7);
+   cout << setw(40) << left << "Number of Observations" << "=  " << trials << "\n";
+   cout << setw(40) << left << "Number of successes" << "=  " << successes << "\n";
+   cout << setw(40) << left << "Sample frequency of occurrence" << "=  " << double(successes) / trials << "\n";
+
+

+ The procedure now defines a table of significance levels: these are the + probabilities that the true occurrence frequency lies outside the calculated + interval: +

+
double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
+
+

+ Some pretty printing of the table header follows: +

+
cout << "\n\n"
+        "_______________________________________________________________________\n"
+        "Confidence        Lower CP       Upper CP       Lower JP       Upper JP\n"
+        " Value (%)        Limit          Limit          Limit          Limit\n"
+        "_______________________________________________________________________\n";
+
+

+ And now for the important part - the intervals themselves - for each + value of alpha, we call find_lower_bound_on_p + and find_lower_upper_on_p + to obtain lower and upper bounds respectively. Note that since we are + calculating a two-sided interval, we must divide the value of alpha in + two. +

+

+ Please note that calculating two separate single sided bounds, + each with risk level α  is not the same thing as calculating a two sided + interval. Had we calculate two single-sided intervals each with a risk + that the true value is outside the interval of α, then: +

+
  • + The risk that it is less than the lower bound is α. +
+

+ and +

+
  • + The risk that it is greater than the upper bound is also α. +
+

+ So the risk it is outside upper or lower bound, + is twice alpha, and the probability + that it is inside the bounds is therefore not nearly as high as one might + have thought. This is why α/2 must be used in the calculations below. +

+

+ In contrast, had we been calculating a single-sided interval, for example: + "Calculate a lower bound so that we are P% sure that the + true occurrence frequency is greater than some value" + then we would not have divided by two. +

+

+ Finally note that binomial_distribution + provides a choice of two methods for the calculation, we print out the + results from both methods in this example: +

+
   for(unsigned i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)
+   {
+      // Confidence value:
+      cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]);
+      // Calculate Clopper Pearson bounds:
+      double l = binomial_distribution<>::find_lower_bound_on_p(
+                     trials, successes, alpha[i]/2);
+      double u = binomial_distribution<>::find_upper_bound_on_p(
+                     trials, successes, alpha[i]/2);
+      // Print Clopper Pearson Limits:
+      cout << fixed << setprecision(5) << setw(15) << right << l;
+      cout << fixed << setprecision(5) << setw(15) << right << u;
+      // Calculate Jeffreys Prior Bounds:
+      l = binomial_distribution<>::find_lower_bound_on_p(
+            trials, successes, alpha[i]/2,
+            binomial_distribution<>::jeffreys_prior_interval);
+      u = binomial_distribution<>::find_upper_bound_on_p(
+            trials, successes, alpha[i]/2,
+            binomial_distribution<>::jeffreys_prior_interval);
+      // Print Jeffreys Prior Limits:
+      cout << fixed << setprecision(5) << setw(15) << right << l;
+      cout << fixed << setprecision(5) << setw(15) << right << u << std::endl;
+   }
+   cout << endl;
+}
+
+

+ And that's all there is to it. Let's see some sample output for a 2 in + 10 success ratio, first for 20 trials: +

+
___________________________________________
+2-Sided Confidence Limits For Success Ratio
+___________________________________________
+
+Number of Observations                  =  20
+Number of successes                     =  4
+Sample frequency of occurrence          =  0.2
+
+
+_______________________________________________________________________
+Confidence        Lower CP       Upper CP       Lower JP       Upper JP
+ Value (%)        Limit          Limit          Limit          Limit
+_______________________________________________________________________
+    50.000        0.12840        0.29588        0.14974        0.26916
+    75.000        0.09775        0.34633        0.11653        0.31861
+    90.000        0.07135        0.40103        0.08734        0.37274
+    95.000        0.05733        0.43661        0.07152        0.40823
+    99.000        0.03576        0.50661        0.04655        0.47859
+    99.900        0.01905        0.58632        0.02634        0.55960
+    99.990        0.01042        0.64997        0.01530        0.62495
+    99.999        0.00577        0.70216        0.00901        0.67897
+
+

+ As you can see, even at the 95% confidence level the bounds are really + quite wide (this example is chosen to be easily compared to the one in + the NIST/SEMATECH + e-Handbook of Statistical Methods. here). + Note also that the Clopper-Pearson calculation method (CP above) produces + quite noticeably more pessimistic estimates than the Jeffreys Prior method + (JP above). +

+

+ Compare that with the program output for 2000 trials: +

+
___________________________________________
+2-Sided Confidence Limits For Success Ratio
+___________________________________________
+
+Number of Observations                  =  2000
+Number of successes                     =  400
+Sample frequency of occurrence          =  0.2000000
+
+
+_______________________________________________________________________
+Confidence        Lower CP       Upper CP       Lower JP       Upper JP
+ Value (%)        Limit          Limit          Limit          Limit
+_______________________________________________________________________
+    50.000        0.19382        0.20638        0.19406        0.20613
+    75.000        0.18965        0.21072        0.18990        0.21047
+    90.000        0.18537        0.21528        0.18561        0.21503
+    95.000        0.18267        0.21821        0.18291        0.21796
+    99.000        0.17745        0.22400        0.17769        0.22374
+    99.900        0.17150        0.23079        0.17173        0.23053
+    99.990        0.16658        0.23657        0.16681        0.23631
+    99.999        0.16233        0.24169        0.16256        0.24143
+
+

+ Now even when the confidence level is very high, the limits are really + quite close to the experimentally calculated value of 0.2. Furthermore + the difference between the two calculation methods is now really quite + small. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binom_size_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binom_size_eg.html new file mode 100644 index 00000000..16e10e88 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binom_size_eg.html @@ -0,0 +1,160 @@ + + + +Estimating Sample Sizes for a Binomial Distribution. + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Imagine you have a critical component that you know will fail in 1 in + N "uses" (for some suitable definition of "use"). + You may want to schedule routine replacement of the component so that + its chance of failure between routine replacements is less than P%. If + the failures follow a binomial distribution (each time the component + is "used" it either fails or does not) then the static member + function binomial_distibution<>::find_maximum_number_of_trials + can be used to estimate the maximum number of "uses" of that + component for some acceptable risk level alpha. +

+

+ The example program binomial_sample_sizes.cpp + demonstrates its usage. It centres on a routine that prints out a table + of maximum sample sizes for various probability thresholds: +

+
void find_max_sample_size(
+   double p,              // success ratio.
+   unsigned successes)    // Total number of observed successes permitted.
+{
+
+

+ The routine then declares a table of probability thresholds: these are + the maximum acceptable probability that successes + or fewer events will be observed. In our example, successes + will be always zero, since we want no component failures, but in other + situations non-zero values may well make sense. +

+
double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
+
+

+ Much of the rest of the program is pretty-printing, the important part + is in the calculation of maximum number of permitted trials for each + value of alpha: +

+
for(unsigned i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)
+{
+   // Confidence value:
+   cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]);
+   // calculate trials:
+   double t = binomial::find_maximum_number_of_trials(
+                  successes, p, alpha[i]);
+   t = floor(t);
+   // Print Trials:
+   cout << fixed << setprecision(5) << setw(15) << right << t << endl;
+}
+
+

+ Note that since we're calculating the maximum number of trials permitted, + we'll err on the safe side and take the floor of the result. Had we been + calculating the minimum number of trials required + to observe a certain number of successes using + find_minimum_number_of_trials + we would have taken the ceiling instead. +

+

+ We'll finish off by looking at some sample output, firstly for a 1 in + 1000 chance of component failure with each use: +

+
________________________
+Maximum Number of Trials
+________________________
+
+Success ratio                           =  0.001
+Maximum Number of "successes" permitted =  0
+
+
+____________________________
+Confidence        Max Number
+ Value (%)        Of Trials
+____________________________
+    50.000            692
+    75.000            287
+    90.000            105
+    95.000             51
+    99.000             10
+    99.900              0
+    99.990              0
+    99.999              0
+
+

+ So 51 "uses" of the component would yield a 95% chance that + no component failures would be observed. +

+

+ Compare that with a 1 in 1 million chance of component failure: +

+
________________________
+Maximum Number of Trials
+________________________
+
+Success ratio                           =  0.0000010
+Maximum Number of "successes" permitted =  0
+
+
+____________________________
+Confidence        Max Number
+ Value (%)        Of Trials
+____________________________
+    50.000         693146
+    75.000         287681
+    90.000         105360
+    95.000          51293
+    99.000          10050
+    99.900           1000
+    99.990            100
+    99.999             10
+
+

+ In this case, even 1000 uses of the component would still yield a less + than 1 in 1000 chance of observing a component failure (i.e. a 99.9% + chance of no failure). +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binomial_coinflip_example.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binomial_coinflip_example.html new file mode 100644 index 00000000..7239542e --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binomial_coinflip_example.html @@ -0,0 +1,274 @@ + + + +Binomial Coin-Flipping Example + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ An example of a Bernoulli + process is coin flipping. A variable in such a sequence may be + called a Bernoulli variable. +

+

+ This example shows using the Binomial distribution to predict the probability + of heads and tails when throwing a coin. +

+

+ The number of correct answers (say heads), X, is distributed as a binomial + random variable with binomial distribution parameters number of trials + (flips) n = 10 and probability (success_fraction) of getting a head p + = 0.5 (a 'fair' coin). +

+

+ (Our coin is assumed fair, but we could easily change the success_fraction + parameter p from 0.5 to some other value to simulate an unfair coin, + say 0.6 for one with chewing gum on the tail, so it is more likely to + fall tails down and heads up). +

+

+ First we need some includes and using statements to be able to use the + binomial distribution, some std input and output, and get started: +

+
#include <boost/math/distributions/binomial.hpp>
+  using boost::math::binomial;
+
+#include <iostream>
+  using std::cout;  using std::endl;  using std::left;
+#include <iomanip>
+  using std::setw;
+
+int main()
+{
+  cout << "Using Binomial distribution to predict how many heads and tails." << endl;
+  try
+  {
+
+

+ See note with the catch block + about why a try and catch block is always a good idea. +

+

+ First, construct a binomial distribution with parameters success_fraction + 1/2, and how many flips. +

+
const double success_fraction = 0.5; // = 50% = 1/2 for a 'fair' coin.
+int flips = 10;
+binomial flip(flips, success_fraction);
+
+cout.precision(4);
+
+

+ Then some examples of using Binomial moments (and echoing the parameters). +

+
cout << "From " << flips << " one can expect to get on average "
+  << mean(flip) << " heads (or tails)." << endl;
+cout << "Mode is " << mode(flip) << endl;
+cout << "Standard deviation is " << standard_deviation(flip) << endl;
+cout << "So about 2/3 will lie within 1 standard deviation and get between "
+  <<  ceil(mean(flip) - standard_deviation(flip))  << " and "
+  << floor(mean(flip) + standard_deviation(flip)) << " correct." << endl;
+cout << "Skewness is " << skewness(flip) << endl;
+// Skewness of binomial distributions is only zero (symmetrical)
+// if success_fraction is exactly one half,
+// for example, when flipping 'fair' coins.
+cout << "Skewness if success_fraction is " << flip.success_fraction()
+  << " is " << skewness(flip) << endl << endl; // Expect zero for a 'fair' coin.
+
+

+ Now we show a variety of predictions on the probability of heads: +

+
cout << "For " << flip.trials() << " coin flips: " << endl;
+cout << "Probability of getting no heads is " << pdf(flip, 0) << endl;
+cout << "Probability of getting at least one head is " << 1. - pdf(flip, 0) << endl;
+
+

+ When we want to calculate the probability for a range or values we can + sum the PDF's: +

+
cout << "Probability of getting 0 or 1 heads is "
+  << pdf(flip, 0) + pdf(flip, 1) << endl; // sum of exactly == probabilities
+
+

+ Or we can use the cdf. +

+
cout << "Probability of getting 0 or 1 (<= 1) heads is " << cdf(flip, 1) << endl;
+cout << "Probability of getting 9 or 10 heads is " << pdf(flip, 9) + pdf(flip, 10) << endl;
+
+

+ Note that using +

+
cout << "Probability of getting 9 or 10 heads is " << 1. - cdf(flip, 8) << endl;
+
+

+ is less accurate than using the complement +

+
cout << "Probability of getting 9 or 10 heads is " << cdf(complement(flip, 8)) << endl;
+
+

+ Since the subtraction may involve cancellation + error, where as cdf(complement(flip, 8)) + does not use such a subtraction internally, and so does not exhibit the + problem. +

+

+ To get the probability for a range of heads, we can either add the pdfs + for each number of heads +

+
cout << "Probability of between 4 and 6 heads (4 or 5 or 6) is "
+  //  P(X == 4) + P(X == 5) + P(X == 6)
+  << pdf(flip, 4) + pdf(flip, 5) + pdf(flip, 6) << endl;
+
+

+ But this is probably less efficient than using the cdf +

+
cout << "Probability of between 4 and 6 heads (4 or 5 or 6) is "
+  // P(X <= 6) - P(X <= 3) == P(X < 4)
+  << cdf(flip, 6) - cdf(flip, 3) << endl;
+
+

+ Certainly for a bigger range like, 3 to 7 +

+
cout << "Probability of between 3 and 7 heads (3, 4, 5, 6 or 7) is "
+  // P(X <= 7) - P(X <= 2) == P(X < 3)
+  << cdf(flip, 7) - cdf(flip, 2) << endl;
+cout << endl;
+
+

+ Finally, print two tables of probability for the exactly + and at least a number of heads. +

+
// Print a table of probability for the exactly a number of heads.
+cout << "Probability of getting exactly (==) heads" << endl;
+for (int successes = 0; successes <= flips; successes++)
+{ // Say success means getting a head (or equally success means getting a tail).
+  double probability = pdf(flip, successes);
+  cout << left << setw(2) << successes << "     " << setw(10)
+    << probability << " or 1 in " << 1. / probability
+    << ", or " << probability * 100. << "%" << endl;
+} // for i
+cout << endl;
+
+// Tabulate the probability of getting between zero heads and 0 upto 10 heads.
+cout << "Probability of getting upto (<=) heads" << endl;
+for (int successes = 0; successes <= flips; successes++)
+{ // Say success means getting a head
+  // (equally success could mean getting a tail).
+  double probability = cdf(flip, successes); // P(X <= heads)
+  cout << setw(2) << successes << "        " << setw(10) << left
+    << probability << " or 1 in " << 1. / probability << ", or "
+    << probability * 100. << "%"<< endl;
+} // for i
+
+

+ The last (0 to 10 heads) must, of course, be 100% probability. +

+
}
+catch(const std::exception& e)
+{
+  //
+
+

+ It is always essential to include try + & catch blocks because default policies are to throw exceptions on + arguments that are out of domain or cause errors like numeric-overflow. +

+

+ Lacking try & catch blocks, the program will abort, whereas the message + below from the thrown exception will give some helpful clues as to the + cause of the problem. +

+
  std::cout <<
+    "\n""Message from thrown exception was:\n   " << e.what() << std::endl;
+}
+
+

+ See binomial_coinflip_example.cpp + for full source code, the program output looks like this: +

+
Using Binomial distribution to predict how many heads and tails.
+From 10 one can expect to get on average 5 heads (or tails).
+Mode is 5
+Standard deviation is 1.581
+So about 2/3 will lie within 1 standard deviation and get between 4 and 6 correct.
+Skewness is 0
+Skewness if success_fraction is 0.5 is 0
+
+For 10 coin flips:
+Probability of getting no heads is 0.0009766
+Probability of getting at least one head is 0.999
+Probability of getting 0 or 1 heads is 0.01074
+Probability of getting 0 or 1 (<= 1) heads is 0.01074
+Probability of getting 9 or 10 heads is 0.01074
+Probability of getting 9 or 10 heads is 0.01074
+Probability of getting 9 or 10 heads is 0.01074
+Probability of between 4 and 6 heads (4 or 5 or 6) is 0.6562
+Probability of between 4 and 6 heads (4 or 5 or 6) is 0.6563
+Probability of between 3 and 7 heads (3, 4, 5, 6 or 7) is 0.8906
+
+Probability of getting exactly (==) heads
+0      0.0009766  or 1 in 1024, or 0.09766%
+1      0.009766   or 1 in 102.4, or 0.9766%
+2      0.04395    or 1 in 22.76, or 4.395%
+3      0.1172     or 1 in 8.533, or 11.72%
+4      0.2051     or 1 in 4.876, or 20.51%
+5      0.2461     or 1 in 4.063, or 24.61%
+6      0.2051     or 1 in 4.876, or 20.51%
+7      0.1172     or 1 in 8.533, or 11.72%
+8      0.04395    or 1 in 22.76, or 4.395%
+9      0.009766   or 1 in 102.4, or 0.9766%
+10     0.0009766  or 1 in 1024, or 0.09766%
+
+Probability of getting upto (<=) heads
+0         0.0009766  or 1 in 1024, or 0.09766%
+1         0.01074    or 1 in 93.09, or 1.074%
+2         0.05469    or 1 in 18.29, or 5.469%
+3         0.1719     or 1 in 5.818, or 17.19%
+4         0.377      or 1 in 2.653, or 37.7%
+5         0.623      or 1 in 1.605, or 62.3%
+6         0.8281     or 1 in 1.208, or 82.81%
+7         0.9453     or 1 in 1.058, or 94.53%
+8         0.9893     or 1 in 1.011, or 98.93%
+9         0.999      or 1 in 1.001, or 99.9%
+10        1          or 1 in 1, or 100%
+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binomial_quiz_example.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binomial_quiz_example.html new file mode 100644 index 00000000..81f54c2e --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/binom_eg/binomial_quiz_example.html @@ -0,0 +1,458 @@ + + + +Binomial Quiz Example + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ A multiple choice test has four possible answers to each of 16 questions. + A student guesses the answer to each question, so the probability of + getting a correct answer on any given question is one in four, a quarter, + 1/4, 25% or fraction 0.25. The conditions of the binomial experiment + are assumed to be met: n = 16 questions constitute the trials; each question + results in one of two possible outcomes (correct or incorrect); the probability + of being correct is 0.25 and is constant if no knowledge about the subject + is assumed; the questions are answered independently if the student's + answer to a question in no way influences his/her answer to another question. +

+

+ First, we need to be able to use the binomial distribution constructor + (and some std input/output, of course). +

+
#include <boost/math/distributions/binomial.hpp>
+  using boost::math::binomial;
+
+#include <iostream>
+  using std::cout; using std::endl;
+  using std::ios; using std::flush; using std::left; using std::right; using std::fixed;
+#include <iomanip>
+  using std::setw; using std::setprecision;
+#include <exception>
+
+

+ The number of correct answers, X, is distributed as a binomial random + variable with binomial distribution parameters: questions n and success + fraction probability p. So we construct a binomial distribution: +

+
int questions = 16; // All the questions in the quiz.
+int answers = 4; // Possible answers to each question.
+double success_fraction = 1. / answers; // If a random guess, p = 1/4 = 0.25.
+binomial quiz(questions, success_fraction);
+
+

+ and display the distribution parameters we used thus: +

+
cout << "In a quiz with " << quiz.trials()
+  << " questions and with a probability of guessing right of "
+  << quiz.success_fraction() * 100 << " %"
+  << " or 1 in " << static_cast<int>(1. / quiz.success_fraction()) << endl;
+
+

+ Show a few probabilities of just guessing: +

+
cout << "Probability of getting none right is " << pdf(quiz, 0) << endl; // 0.010023
+cout << "Probability of getting exactly one right is " << pdf(quiz, 1) << endl;
+cout << "Probability of getting exactly two right is " << pdf(quiz, 2) << endl;
+int pass_score = 11;
+cout << "Probability of getting exactly " << pass_score << " answers right by chance is "
+  << pdf(quiz, pass_score) << endl;
+cout << "Probability of getting all " << questions << " answers right by chance is "
+  << pdf(quiz, questions) << endl;
+
+
Probability of getting none right is 0.0100226
+Probability of getting exactly one right is 0.0534538
+Probability of getting exactly two right is 0.133635
+Probability of getting exactly 11 right is 0.000247132
+Probability of getting exactly all 16 answers right by chance is 2.32831e-010
+
+

+ These don't give any encouragement to guessers! +

+

+ We can tabulate the 'getting exactly right' ( == ) probabilities thus: +

+
cout << "\n" "Guessed Probability" << right << endl;
+for (int successes = 0; successes <= questions; successes++)
+{
+  double probability = pdf(quiz, successes);
+  cout << setw(2) << successes << "      " << probability << endl;
+}
+cout << endl;
+
+
Guessed Probability
+ 0      0.0100226
+ 1      0.0534538
+ 2      0.133635
+ 3      0.207876
+ 4      0.225199
+ 5      0.180159
+ 6      0.110097
+ 7      0.0524273
+ 8      0.0196602
+ 9      0.00582526
+10      0.00135923
+11      0.000247132
+12      3.43239e-005
+13      3.5204e-006
+14      2.51457e-007
+15      1.11759e-008
+16      2.32831e-010
+
+

+ Then we can add the probabilities of some 'exactly right' like this: +

+
cout << "Probability of getting none or one right is " << pdf(quiz, 0) + pdf(quiz, 1) << endl;
+
+
Probability of getting none or one right is 0.0634764
+
+

+ But if more than a couple of scores are involved, it is more convenient + (and may be more accurate) to use the Cumulative Distribution Function + (cdf) instead: +

+
cout << "Probability of getting none or one right is " << cdf(quiz, 1) << endl;
+
+
Probability of getting none or one right is 0.0634764
+
+

+ Since the cdf is inclusive, we can get the probability of getting up + to 10 right ( <= ) +

+
cout << "Probability of getting <= 10 right (to fail) is " << cdf(quiz, 10) << endl;
+
+
Probability of getting <= 10 right (to fail) is 0.999715
+
+

+ To get the probability of getting 11 or more right (to pass), it is tempting + to use +

+
1 - cdf(quiz, 10)
+

+ to get the probability of > 10 +

+
cout << "Probability of getting > 10 right (to pass) is " << 1 - cdf(quiz, 10) << endl;
+
+
Probability of getting > 10 right (to pass) is 0.000285239
+
+

+ But this should be resisted in favor of using the complements + function (see why complements?). +

+
cout << "Probability of getting > 10 right (to pass) is " << cdf(complement(quiz, 10)) << endl;
+
+
Probability of getting > 10 right (to pass) is 0.000285239
+
+

+ And we can check that these two, <= 10 and > 10, add up to unity. +

+
BOOST_ASSERT((cdf(quiz, 10) + cdf(complement(quiz, 10))) == 1.);
+
+

+ If we want a < rather than a <= test, because the CDF is inclusive, + we must subtract one from the score. +

+
cout << "Probability of getting less than " << pass_score
+  << " (< " << pass_score << ") answers right by guessing is "
+  << cdf(quiz, pass_score -1) << endl;
+
+
Probability of getting less than 11 (< 11) answers right by guessing is 0.999715
+
+

+ and similarly to get a >= rather than a > test we also need to + subtract one from the score (and can again check the sum is unity). This + is because if the cdf is inclusive, then its complement + must be exclusive otherwise there would be one possible + outcome counted twice! +

+
cout << "Probability of getting at least " << pass_score
+  << "(>= " << pass_score << ") answers right by guessing is "
+  << cdf(complement(quiz, pass_score-1))
+  << ", only 1 in " << 1/cdf(complement(quiz, pass_score-1)) << endl;
+
+BOOST_ASSERT((cdf(quiz, pass_score -1) + cdf(complement(quiz, pass_score-1))) == 1);
+
+
Probability of getting at least 11 (>= 11) answers right by guessing is 0.000285239, only 1 in 3505.83
+
+

+ Finally we can tabulate some probabilities: +

+
cout << "\n" "At most (<=)""\n""Guessed OK   Probability" << right << endl;
+for (int score = 0; score <= questions; score++)
+{
+  cout << setw(2) << score << "           " << setprecision(10)
+    << cdf(quiz, score) << endl;
+}
+cout << endl;
+
+
At most (<=)
+Guessed OK   Probability
+ 0           0.01002259576
+ 1           0.0634764398
+ 2           0.1971110499
+ 3           0.4049871101
+ 4           0.6301861752
+ 5           0.8103454274
+ 6           0.9204427481
+ 7           0.9728700437
+ 8           0.9925302796
+ 9           0.9983555346
+10           0.9997147608
+11           0.9999618928
+12           0.9999962167
+13           0.9999997371
+14           0.9999999886
+15           0.9999999998
+16           1
+
+
cout << "\n" "At least (>)""\n""Guessed OK   Probability" << right << endl;
+for (int score = 0; score <= questions; score++)
+{
+  cout << setw(2) << score << "           "  << setprecision(10)
+    << cdf(complement(quiz, score)) << endl;
+}
+
+
At least (>)
+Guessed OK   Probability
+ 0           0.9899774042
+ 1           0.9365235602
+ 2           0.8028889501
+ 3           0.5950128899
+ 4           0.3698138248
+ 5           0.1896545726
+ 6           0.07955725188
+ 7           0.02712995629
+ 8           0.00746972044
+ 9           0.001644465374
+10           0.0002852391917
+11           3.810715862e-005
+12           3.783265129e-006
+13           2.628657967e-007
+14           1.140870154e-008
+15           2.328306437e-010
+16           0
+
+

+ We now consider the probabilities of ranges + of correct guesses. +

+

+ First, calculate the probability of getting a range of guesses right, + by adding the exact probabilities of each from low ... high. +

+
int low = 3; // Getting at least 3 right.
+int high = 5; // Getting as most 5 right.
+double sum = 0.;
+for (int i = low; i <= high; i++)
+{
+  sum += pdf(quiz, i);
+}
+cout.precision(4);
+cout << "Probability of getting between "
+  << low << " and " << high << " answers right by guessing is "
+  << sum  << endl; // 0.61323
+
+
Probability of getting between 3 and 5 answers right by guessing is 0.6132
+
+

+ Or, usually better, we can use the difference of cdfs instead: +

+
cout << "Probability of getting between " << low << " and " << high << " answers right by guessing is "
+  <<  cdf(quiz, high) - cdf(quiz, low - 1) << endl; // 0.61323
+
+
Probability of getting between 3 and 5 answers right by guessing is 0.6132
+
+

+ And we can also try a few more combinations of high and low choices: +

+
low = 1; high = 6;
+cout << "Probability of getting between " << low << " and " << high << " answers right by guessing is "
+  <<  cdf(quiz, high) - cdf(quiz, low - 1) << endl; // 1 and 6 P= 0.91042
+low = 1; high = 8;
+cout << "Probability of getting between " << low << " and " << high << " answers right by guessing is "
+  <<  cdf(quiz, high) - cdf(quiz, low - 1) << endl; // 1 <= x 8 P = 0.9825
+low = 4; high = 4;
+cout << "Probability of getting between " << low << " and " << high << " answers right by guessing is "
+  <<  cdf(quiz, high) - cdf(quiz, low - 1) << endl; // 4 <= x 4 P = 0.22520
+
+
Probability of getting between 1 and 6 answers right by guessing is 0.9104
+Probability of getting between 1 and 8 answers right by guessing is 0.9825
+Probability of getting between 4 and 4 answers right by guessing is 0.2252
+
+
+ + Using + Binomial distribution moments +
+

+ Using moments of the distribution, we can say more about the spread of + results from guessing. +

+
cout << "By guessing, on average, one can expect to get " << mean(quiz) << " correct answers." << endl;
+cout << "Standard deviation is " << standard_deviation(quiz) << endl;
+cout << "So about 2/3 will lie within 1 standard deviation and get between "
+  <<  ceil(mean(quiz) - standard_deviation(quiz))  << " and "
+  << floor(mean(quiz) + standard_deviation(quiz)) << " correct." << endl;
+cout << "Mode (the most frequent) is " << mode(quiz) << endl;
+cout << "Skewness is " << skewness(quiz) << endl;
+
+
By guessing, on average, one can expect to get 4 correct answers.
+Standard deviation is 1.732
+So about 2/3 will lie within 1 standard deviation and get between 3 and 5 correct.
+Mode (the most frequent) is 4
+Skewness is 0.2887
+
+
+ + Quantiles +
+

+ The quantiles (percentiles or percentage points) for a few probability + levels: +

+
cout << "Quartiles " << quantile(quiz, 0.25) << " to "
+  << quantile(complement(quiz, 0.25)) << endl; // Quartiles
+cout << "1 standard deviation " << quantile(quiz, 0.33) << " to "
+  << quantile(quiz, 0.67) << endl; // 1 sd
+cout << "Deciles " << quantile(quiz, 0.1)  << " to "
+  << quantile(complement(quiz, 0.1))<< endl; // Deciles
+cout << "5 to 95% " << quantile(quiz, 0.05)  << " to "
+  << quantile(complement(quiz, 0.05))<< endl; // 5 to 95%
+cout << "2.5 to 97.5% " << quantile(quiz, 0.025) << " to "
+  <<  quantile(complement(quiz, 0.025)) << endl; // 2.5 to 97.5%
+cout << "2 to 98% " << quantile(quiz, 0.02)  << " to "
+  << quantile(complement(quiz, 0.02)) << endl; //  2 to 98%
+
+cout << "If guessing then percentiles 1 to 99% will get " << quantile(quiz, 0.01)
+  << " to " << quantile(complement(quiz, 0.01)) << " right." << endl;
+
+

+ Notice that these output integral values because the default policy is + integer_round_outwards. +

+
Quartiles 2 to 5
+1 standard deviation 2 to 5
+Deciles 1 to 6
+5 to 95% 0 to 7
+2.5 to 97.5% 0 to 8
+2 to 98% 0 to 8
+
+

+ Quantiles values are controlled by the understanding + discrete quantiles quantile policy chosen. The default is integer_round_outwards, so the lower + quantile is rounded down, and the upper quantile is rounded up. +

+

+ But we might believe that the real values tell us a little more - see + discrete functions. +

+

+ We could control the policy for all + distributions by +

+
#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real
+
+at the head of the program would make this policy apply
+
+

+ to this one, and only, translation unit. +

+

+ Or we can now create a (typedef for) policy that has discrete quantiles + real (here avoiding any 'using namespaces ...' statements): +

+
using boost::math::policies::policy;
+using boost::math::policies::discrete_quantile;
+using boost::math::policies::real;
+using boost::math::policies::integer_round_outwards; // Default.
+typedef boost::math::policies::policy<discrete_quantile<real> > real_quantile_policy;
+
+

+ Add a custom binomial distribution called +

+
real_quantile_binomial
+

+ that uses +

+
real_quantile_policy
+
using boost::math::binomial_distribution;
+typedef binomial_distribution<double, real_quantile_policy> real_quantile_binomial;
+
+

+ Construct an object of this custom distribution: +

+
real_quantile_binomial quiz_real(questions, success_fraction);
+
+

+ And use this to show some quantiles - that now have real rather than + integer values. +

+
cout << "Quartiles " << quantile(quiz, 0.25) << " to "
+  << quantile(complement(quiz_real, 0.25)) << endl; // Quartiles 2 to 4.6212
+cout << "1 standard deviation " << quantile(quiz_real, 0.33) << " to "
+  << quantile(quiz_real, 0.67) << endl; // 1 sd 2.6654 4.194
+cout << "Deciles " << quantile(quiz_real, 0.1)  << " to "
+  << quantile(complement(quiz_real, 0.1))<< endl; // Deciles 1.3487 5.7583
+cout << "5 to 95% " << quantile(quiz_real, 0.05)  << " to "
+  << quantile(complement(quiz_real, 0.05))<< endl; // 5 to 95% 0.83739 6.4559
+cout << "2.5 to 97.5% " << quantile(quiz_real, 0.025) << " to "
+  <<  quantile(complement(quiz_real, 0.025)) << endl; // 2.5 to 97.5% 0.42806 7.0688
+cout << "2 to 98% " << quantile(quiz_real, 0.02)  << " to "
+  << quantile(complement(quiz_real, 0.02)) << endl; //  2 to 98% 0.31311 7.7880
+
+cout << "If guessing, then percentiles 1 to 99% will get " << quantile(quiz_real, 0.01)
+  << " to " << quantile(complement(quiz_real, 0.01)) << " right." << endl;
+
+
Real Quantiles
+Quartiles 2 to 4.621
+1 standard deviation 2.665 to 4.194
+Deciles 1.349 to 5.758
+5 to 95% 0.8374 to 6.456
+2.5 to 97.5% 0.4281 to 7.069
+2 to 98% 0.3131 to 7.252
+If guessing then percentiles 1 to 99% will get 0 to 7.788 right.
+
+

+ See binomial_quiz_example.cpp + for full source code and output. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/c_sharp.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/c_sharp.html new file mode 100644 index 00000000..bec369ff --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/c_sharp.html @@ -0,0 +1,58 @@ + + + +Using the Distributions from Within C# + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ The distributions in this library can be used from the C# programming language + when they are built using Microsoft's Common Language Runtime (CLR) option. +

+

+ An example of this kind of usage is given in the Distribution + Explorer example. See boost-root/libs/math/dot_net_example + for the source code: the application consists of a C++ .dll that contains + the actual distributions, and a C# GUI that allows you to explore their + properties. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg.html new file mode 100644 index 00000000..ac3b4550 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg.html @@ -0,0 +1,55 @@ + + + +Chi Squared Distribution Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ + +
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_intervals.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_intervals.html new file mode 100644 index 00000000..b01b22ca --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_intervals.html @@ -0,0 +1,236 @@ + + + +Confidence Intervals on the Standard Deviation + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Once you have calculated the standard deviation for your data, a legitimate + question to ask is "How reliable is the calculated standard deviation?". + For this situation the Chi Squared distribution can be used to calculate + confidence intervals for the standard deviation. +

+

+ The full example code & sample output is in chi_square_std_dev_test.cpp. +

+

+ We'll begin by defining the procedure that will calculate and print out + the confidence intervals: +

+
void confidence_limits_on_std_deviation(
+     double Sd,    // Sample Standard Deviation
+     unsigned N)   // Sample size
+{
+
+

+ We'll begin by printing out some general information: +

+
cout <<
+   "________________________________________________\n"
+   "2-Sided Confidence Limits For Standard Deviation\n"
+   "________________________________________________\n\n";
+cout << setprecision(7);
+cout << setw(40) << left << "Number of Observations" << "=  " << N << "\n";
+cout << setw(40) << left << "Standard Deviation" << "=  " << Sd << "\n";
+
+

+ and then define a table of significance levels for which we'll calculate + intervals: +

+
double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
+
+

+ The distribution we'll need to calculate the confidence intervals is + a Chi Squared distribution, with N-1 degrees of freedom: +

+
chi_squared dist(N - 1);
+
+

+ For each value of alpha, the formula for the confidence interval is given + by: +

+

+ +

+

+ Where is the upper critical value, and is + the lower critical value of the Chi Squared distribution. +

+

+ In code we begin by printing out a table header: +

+
cout << "\n\n"
+        "_____________________________________________\n"
+        "Confidence          Lower          Upper\n"
+        " Value (%)          Limit          Limit\n"
+        "_____________________________________________\n";
+
+

+ and then loop over the values of alpha and calculate the intervals for + each: remember that the lower critical value is the same as the quantile, + and the upper critical value is the same as the quantile from the complement + of the probability: +

+
for(unsigned i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)
+{
+   // Confidence value:
+   cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]);
+   // Calculate limits:
+   double lower_limit = sqrt((N - 1) * Sd * Sd / quantile(complement(dist, alpha[i] / 2)));
+   double upper_limit = sqrt((N - 1) * Sd * Sd / quantile(dist, alpha[i] / 2));
+   // Print Limits:
+   cout << fixed << setprecision(5) << setw(15) << right << lower_limit;
+   cout << fixed << setprecision(5) << setw(15) << right << upper_limit << endl;
+}
+cout << endl;
+
+

+ To see some example output we'll use the gear + data from the NIST/SEMATECH + e-Handbook of Statistical Methods.. The data represents measurements + of gear diameter from a manufacturing process. +

+
________________________________________________
+2-Sided Confidence Limits For Standard Deviation
+________________________________________________
+
+Number of Observations                  =  100
+Standard Deviation                      =  0.006278908
+
+
+_____________________________________________
+Confidence          Lower          Upper
+ Value (%)          Limit          Limit
+_____________________________________________
+    50.000        0.00601        0.00662
+    75.000        0.00582        0.00685
+    90.000        0.00563        0.00712
+    95.000        0.00551        0.00729
+    99.000        0.00530        0.00766
+    99.900        0.00507        0.00812
+    99.990        0.00489        0.00855
+    99.999        0.00474        0.00895
+
+

+ So at the 95% confidence level we conclude that the standard deviation + is between 0.00551 and 0.00729. +

+
+ + Confidence + intervals as a function of the number of observations +
+

+ Similarly, we can also list the confidence intervals for the standard + deviation for the common confidence levels 95%, for increasing numbers + of observations. +

+

+ The standard deviation used to compute these values is unity, so the + limits listed are multipliers for any + particular standard deviation. For example, given a standard deviation + of 0.0062789 as in the example above; for 100 observations the multiplier + is 0.8780 giving the lower confidence limit of 0.8780 * 0.006728 = 0.00551. +

+
____________________________________________________
+Confidence level (two-sided)            =  0.0500000
+Standard Deviation                      =  1.0000000
+________________________________________
+Observations        Lower          Upper
+                    Limit          Limit
+________________________________________
+         2         0.4461        31.9102
+         3         0.5207         6.2847
+         4         0.5665         3.7285
+         5         0.5991         2.8736
+         6         0.6242         2.4526
+         7         0.6444         2.2021
+         8         0.6612         2.0353
+         9         0.6755         1.9158
+        10         0.6878         1.8256
+        15         0.7321         1.5771
+        20         0.7605         1.4606
+        30         0.7964         1.3443
+        40         0.8192         1.2840
+        50         0.8353         1.2461
+        60         0.8476         1.2197
+       100         0.8780         1.1617
+       120         0.8875         1.1454
+      1000         0.9580         1.0459
+     10000         0.9863         1.0141
+     50000         0.9938         1.0062
+    100000         0.9956         1.0044
+   1000000         0.9986         1.0014
+
+

+ With just 2 observations the limits are from 0.445 + up to to 31.9, so the standard deviation + might be about half the observed value + up to 30 times the observed value! +

+

+ Estimating a standard deviation with just a handful of values leaves + a very great uncertainty, especially the upper limit. Note especially + how far the upper limit is skewed from the most likely standard deviation. +

+

+ Even for 10 observations, normally considered a reasonable number, the + range is still from 0.69 to 1.8, about a range of 0.7 to 2, and is still + highly skewed with an upper limit twice + the median. +

+

+ When we have 1000 observations, the estimate of the standard deviation + is starting to look convincing, with a range from 0.95 to 1.05 - now + near symmetrical, but still about + or - 5%. +

+

+ Only when we have 10000 or more repeated observations can we start to + be reasonably confident (provided we are sure that other factors like + drift are not creeping in). +

+

+ For 10000 observations, the interval is 0.99 to 1.1 - finally a really + convincing + or -1% confidence. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_size.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_size.html new file mode 100644 index 00000000..efc12fde --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_size.html @@ -0,0 +1,182 @@ + + + +Estimating the Required Sample Sizes for a Chi-Square Test for the Standard Deviation + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Suppose we conduct a Chi Squared test for standard deviation and the + result is borderline, a legitimate question to ask is "How large + would the sample size have to be in order to produce a definitive result?" +

+

+ The class template chi_squared_distribution + has a static method find_degrees_of_freedom + that will calculate this value for some acceptable risk of type I failure + alpha, type II failure beta, + and difference from the standard deviation diff. + Please note that the method used works on variance, and not standard + deviation as is usual for the Chi Squared Test. +

+

+ The code for this example is located in chi_square_std_dev_test.cpp. +

+

+ We begin by defining a procedure to print out the sample sizes required + for various risk levels: +

+
void chi_squared_sample_sized(
+     double diff,      // difference from variance to detect
+     double variance)  // true variance
+{
+
+

+ The procedure begins by printing out the input data: +

+
using namespace std;
+using namespace boost::math;
+
+// Print out general info:
+cout <<
+   "_____________________________________________________________\n"
+   "Estimated sample sizes required for various confidence levels\n"
+   "_____________________________________________________________\n\n";
+cout << setprecision(5);
+cout << setw(40) << left << "True Variance" << "=  " << variance << "\n";
+cout << setw(40) << left << "Difference to detect" << "=  " << diff << "\n";
+
+

+ And defines a table of significance levels for which we'll calculate + sample sizes: +

+
double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
+
+

+ For each value of alpha we can calculate two sample sizes: one where + the sample variance is less than the true value by diff + and one where it is greater than the true value by diff. + Thanks to the asymmetric nature of the Chi Squared distribution these + two values will not be the same, the difference in their calculation + differs only in the sign of diff that's passed to + find_degrees_of_freedom. + Finally in this example we'll simply things, and let risk level beta + be the same as alpha: +

+
cout << "\n\n"
+        "_______________________________________________________________\n"
+        "Confidence       Estimated          Estimated\n"
+        " Value (%)      Sample Size        Sample Size\n"
+        "                (lower one         (upper one\n"
+        "                 sided test)        sided test)\n"
+        "_______________________________________________________________\n";
+//
+// Now print out the data for the table rows.
+//
+for(unsigned i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)
+{
+   // Confidence value:
+   cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]);
+   // calculate df for a lower single sided test:
+   double df = chi_squared::find_degrees_of_freedom(
+      -diff, alpha[i], alpha[i], variance);
+   // convert to sample size:
+   double size = ceil(df) + 1;
+   // Print size:
+   cout << fixed << setprecision(0) << setw(16) << right << size;
+   // calculate df for an upper single sided test:
+   df = chi_squared::find_degrees_of_freedom(
+      diff, alpha[i], alpha[i], variance);
+   // convert to sample size:
+   size = ceil(df) + 1;
+   // Print size:
+   cout << fixed << setprecision(0) << setw(16) << right << size << endl;
+}
+cout << endl;
+
+

+ For some example output, consider the silicon + wafer data from the NIST/SEMATECH + e-Handbook of Statistical Methods.. In this scenario a supplier + of 100 ohm.cm silicon wafers claims that his fabrication process can + produce wafers with sufficient consistency so that the standard deviation + of resistivity for the lot does not exceed 10 ohm.cm. A sample of N = + 10 wafers taken from the lot has a standard deviation of 13.97 ohm.cm, + and the question we ask ourselves is "How large would our sample + have to be to reliably detect this difference?". +

+

+ To use our procedure above, we have to convert the standard deviations + to variance (square them), after which the program output looks like + this: +

+
_____________________________________________________________
+Estimated sample sizes required for various confidence levels
+_____________________________________________________________
+
+True Variance                           =  100.00000
+Difference to detect                    =  95.16090
+
+
+_______________________________________________________________
+Confidence       Estimated          Estimated
+ Value (%)      Sample Size        Sample Size
+                (lower one         (upper one
+                 sided test)        sided test)
+_______________________________________________________________
+    50.000               2               2
+    75.000               2              10
+    90.000               4              32
+    95.000               5              51
+    99.000               7              99
+    99.900              11             174
+    99.990              15             251
+    99.999              20             330
+
+

+ In this case we are interested in a upper single sided test. So for example, + if the maximum acceptable risk of falsely rejecting the null-hypothesis + is 0.05 (Type I error), and the maximum acceptable risk of failing to + reject the null-hypothesis is also 0.05 (Type II error), we estimate + that we would need a sample size of 51. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_test.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_test.html new file mode 100644 index 00000000..6416e691 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/cs_eg/chi_sq_test.html @@ -0,0 +1,297 @@ + + + +Chi-Square Test for the Standard Deviation + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ We use this test to determine whether the standard deviation of a sample + differs from a specified value. Typically this occurs in process change + situations where we wish to compare the standard deviation of a new process + to an established one. +

+

+ The code for this example is contained in chi_square_std_dev_test.cpp, + and we'll begin by defining the procedure that will print out the test + statistics: +

+
void chi_squared_test(
+    double Sd,     // Sample std deviation
+    double D,      // True std deviation
+    unsigned N,    // Sample size
+    double alpha)  // Significance level
+{
+
+

+ The procedure begins by printing a summary of the input data: +

+
using namespace std;
+using namespace boost::math;
+
+// Print header:
+cout <<
+   "______________________________________________\n"
+   "Chi Squared test for sample standard deviation\n"
+   "______________________________________________\n\n";
+cout << setprecision(5);
+cout << setw(55) << left << "Number of Observations" << "=  " << N << "\n";
+cout << setw(55) << left << "Sample Standard Deviation" << "=  " << Sd << "\n";
+cout << setw(55) << left << "Expected True Standard Deviation" << "=  " << D << "\n\n";
+
+

+ The test statistic (T) is simply the ratio of the sample and "true" + standard deviations squared, multiplied by the number of degrees of freedom + (the sample size less one): +

+
double t_stat = (N - 1) * (Sd / D) * (Sd / D);
+cout << setw(55) << left << "Test Statistic" << "=  " << t_stat << "\n";
+
+

+ The distribution we need to use, is a Chi Squared distribution with N-1 + degrees of freedom: +

+
chi_squared dist(N - 1);
+
+

+ The various hypothesis that can be tested are summarised in the following + table: +

+
++++ + + + + + + + + + + + + + + + + + + + + + + +
+

+ Hypothesis +

+
+

+ Test +

+
+

+ The null-hypothesis: there is no difference in standard deviation + from the specified value +

+
+

+ Reject if T < χ2(1-alpha/2; N-1) or T > χ2(alpha/2; N-1) +

+
+

+ The alternative hypothesis: there is a difference in standard + deviation from the specified value +

+
+

+ Reject if χ2(1-alpha/2; N-1) >= T >= χ2(alpha/2; N-1) +

+
+

+ The alternative hypothesis: the standard deviation is less + than the specified value +

+
+

+ Reject if χ2(1-alpha; N-1) <= T +

+
+

+ The alternative hypothesis: the standard deviation is greater + than the specified value +

+
+

+ Reject if χ2(alpha; N-1) >= T +

+
+

+ Where χ2(alpha; N-1) is the upper critical value of the Chi Squared distribution, + and χ2(1-alpha; N-1) is the lower critical value. +

+

+ Recall that the lower critical value is the same as the quantile, and + the upper critical value is the same as the quantile from the complement + of the probability, that gives us the following code to calculate the + critical values: +

+
double ucv = quantile(complement(dist, alpha));
+double ucv2 = quantile(complement(dist, alpha / 2));
+double lcv = quantile(dist, alpha);
+double lcv2 = quantile(dist, alpha / 2);
+cout << setw(55) << left << "Upper Critical Value at alpha: " << "=  "
+   << setprecision(3) << scientific << ucv << "\n";
+cout << setw(55) << left << "Upper Critical Value at alpha/2: " << "=  "
+   << setprecision(3) << scientific << ucv2 << "\n";
+cout << setw(55) << left << "Lower Critical Value at alpha: " << "=  "
+   << setprecision(3) << scientific << lcv << "\n";
+cout << setw(55) << left << "Lower Critical Value at alpha/2: " << "=  "
+   << setprecision(3) << scientific << lcv2 << "\n\n";
+
+

+ Now that we have the critical values, we can compare these to our test + statistic, and print out the result of each hypothesis and test: +

+
cout << setw(55) << left <<
+   "Results for Alternative Hypothesis and alpha" << "=  "
+   << setprecision(4) << fixed << alpha << "\n\n";
+cout << "Alternative Hypothesis              Conclusion\n";
+
+cout << "Standard Deviation != " << setprecision(3) << fixed << D << "            ";
+if((ucv2 < t_stat) || (lcv2 > t_stat))
+   cout << "ACCEPTED\n";
+else
+   cout << "REJECTED\n";
+
+cout << "Standard Deviation  < " << setprecision(3) << fixed << D << "            ";
+if(lcv > t_stat)
+   cout << "ACCEPTED\n";
+else
+   cout << "REJECTED\n";
+
+cout << "Standard Deviation  > " << setprecision(3) << fixed << D << "            ";
+if(ucv < t_stat)
+   cout << "ACCEPTED\n";
+else
+   cout << "REJECTED\n";
+cout << endl << endl;
+
+

+ To see some example output we'll use the gear + data from the NIST/SEMATECH + e-Handbook of Statistical Methods.. The data represents measurements + of gear diameter from a manufacturing process. The program output is + deliberately designed to mirror the DATAPLOT output shown in the NIST + Handbook Example. +

+
______________________________________________
+Chi Squared test for sample standard deviation
+______________________________________________
+
+Number of Observations                                 =  100
+Sample Standard Deviation                              =  0.00628
+Expected True Standard Deviation                       =  0.10000
+
+Test Statistic                                         =  0.39030
+CDF of test statistic:                                 =  1.438e-099
+Upper Critical Value at alpha:                         =  1.232e+002
+Upper Critical Value at alpha/2:                       =  1.284e+002
+Lower Critical Value at alpha:                         =  7.705e+001
+Lower Critical Value at alpha/2:                       =  7.336e+001
+
+Results for Alternative Hypothesis and alpha           =  0.0500
+
+Alternative Hypothesis              Conclusion
+Standard Deviation != 0.100            ACCEPTED
+Standard Deviation  < 0.100            ACCEPTED
+Standard Deviation  > 0.100            REJECTED
+
+

+ In this case we are testing whether the sample standard deviation is + 0.1, and the null-hypothesis is rejected, so we conclude that the standard + deviation is not 0.1. +

+

+ For an alternative example, consider the silicon + wafer data again from the NIST/SEMATECH + e-Handbook of Statistical Methods.. In this scenario a supplier + of 100 ohm.cm silicon wafers claims that his fabrication process can + produce wafers with sufficient consistency so that the standard deviation + of resistivity for the lot does not exceed 10 ohm.cm. A sample of N = + 10 wafers taken from the lot has a standard deviation of 13.97 ohm.cm, + and the question we ask ourselves is "Is the suppliers claim correct?". +

+

+ The program output now looks like this: +

+
______________________________________________
+Chi Squared test for sample standard deviation
+______________________________________________
+
+Number of Observations                                 =  10
+Sample Standard Deviation                              =  13.97000
+Expected True Standard Deviation                       =  10.00000
+
+Test Statistic                                         =  17.56448
+CDF of test statistic:                                 =  9.594e-001
+Upper Critical Value at alpha:                         =  1.692e+001
+Upper Critical Value at alpha/2:                       =  1.902e+001
+Lower Critical Value at alpha:                         =  3.325e+000
+Lower Critical Value at alpha/2:                       =  2.700e+000
+
+Results for Alternative Hypothesis and alpha           =  0.0500
+
+Alternative Hypothesis              Conclusion
+Standard Deviation != 10.000            REJECTED
+Standard Deviation  < 10.000            REJECTED
+Standard Deviation  > 10.000            ACCEPTED
+
+

+ In this case, our null-hypothesis is that the standard deviation of the + sample is less than 10: this hypothesis is rejected in the analysis above, + and so we reject the manufacturers claim. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/dist_construct_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/dist_construct_eg.html new file mode 100644 index 00000000..ce0b91d8 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/dist_construct_eg.html @@ -0,0 +1,333 @@ + + + +Distribution Construction Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ The structure of distributions is rather different from some other statistical + libraries, for example, those written in less object-oriented language + like FORTRAN and C: these provide a few arguments to each free function. +

+

+ Boost.Math library provides each distribution as a template C++ class. + A distribution is constructed with a few arguments, and then member and + non-member functions are used to find values of the distribution, often + a function of a random variate. +

+

+ For this demonstration, first we need some includes to access the negative + binomial distribution (and the binomial, beta and gamma distributions too). +

+

+ To demonstrate the use with a high precision User-defined floating-point + type cpp_dec_float we also + need an include from Boost.Multiprecision. +

+
#include <boost/math/distributions/negative_binomial.hpp> // for negative_binomial_distribution
+  using boost::math::negative_binomial_distribution; // default type is double.
+  using boost::math::negative_binomial; // typedef provides default type is double.
+#include <boost/math/distributions/binomial.hpp> // for binomial_distribution.
+#include <boost/math/distributions/beta.hpp> // for beta_distribution.
+#include <boost/math/distributions/gamma.hpp> // for gamma_distribution.
+#include <boost/math/distributions/normal.hpp> // for normal_distribution.
+
+#include <boost/multiprecision/cpp_dec_float.hpp> // for cpp_dec_float_100
+
+

+ Several examples of constructing distributions follow: +

+

+ First, a negative binomial distribution with 8 successes and a success + fraction 0.25, 25% or 1 in 4, is constructed like this: +

+
boost::math::negative_binomial_distribution<double> mydist0(8., 0.25);
+
+

+ But this is inconveniently long, so we might be tempted to write +

+
using namespace boost::math;
+
+

+ but this might risk ambiguity with names in std + random so much + better is explicit using boost::math:: + statements, for example: +

+
using boost::math::negative_binomial_distribution;
+
+

+ and we can still reduce typing. +

+

+ Since the vast majority of applications use will be using double precision, the template argument + to the distribution (RealType) + defaults to type double, so + we can also write: +

+
negative_binomial_distribution<> mydist9(8., 0.25); // Uses default `RealType = double`.
+
+

+ But the name negative_binomial_distribution + is still inconveniently long, so, for most distributions, a convenience + typedef is provided, for example: +

+
typedef negative_binomial_distribution<double> negative_binomial; // Reserved name of type double.
+
+
+ + + + + +
[Caution]Caution

+ This convenience typedef is not provided + if a clash would occur with the name of a function: currently only beta and gamma + fall into this category. +

+

+ So, after a using statement, +

+
using boost::math::negative_binomial;
+
+

+ we have a convenient typedef to negative_binomial_distribution<double>: +

+
negative_binomial mydist(8., 0.25);
+
+

+ Some more examples using the convenience typedef: +

+
negative_binomial mydist10(5., 0.4); // Both arguments double.
+
+

+ And automatic conversion takes place, so you can use integers and floats: +

+
negative_binomial mydist11(5, 0.4); // Using provided typedef double, int and double arguments.
+
+

+ This is probably the most common usage. +

+
negative_binomial mydist12(5., 0.4F); // Double and float arguments.
+negative_binomial mydist13(5, 1); // Both arguments integer.
+
+

+ Similarly for most other distributions like the binomial. +

+
binomial mybinomial(1, 0.5); // is more concise than
+binomial_distribution<> mybinomd1(1, 0.5);
+
+

+ For cases when the typdef distribution name would clash with a math special + function (currently only beta and gamma) the typedef is deliberately not + provided, and the longer version of the name must be used. For example + do not use: +

+
using boost::math::beta;
+beta mybetad0(1, 0.5); // Error beta is a math FUNCTION!
+
+

+ Which produces the error messages: +

+
error C2146: syntax error : missing ';' before identifier 'mybetad0'
+warning C4551: function call missing argument list
+error C3861: 'mybetad0': identifier not found
+
+

+ Instead you should use: +

+
using boost::math::beta_distribution;
+beta_distribution<> mybetad1(1, 0.5);
+
+

+ or for the gamma distribution: +

+
gamma_distribution<> mygammad1(1, 0.5);
+
+

+ We can, of course, still provide the type explicitly thus: +

+
// Explicit double precision:  both arguments are double:
+negative_binomial_distribution<double>        mydist1(8., 0.25);
+
+// Explicit float precision, double arguments are truncated to float:
+negative_binomial_distribution<float>         mydist2(8., 0.25);
+
+// Explicit float precision, integer & double arguments converted to float:
+negative_binomial_distribution<float>         mydist3(8, 0.25);
+
+// Explicit float precision, float arguments, so no conversion:
+negative_binomial_distribution<float>         mydist4(8.F, 0.25F);
+
+// Explicit float precision, integer arguments promoted to float.
+negative_binomial_distribution<float>         mydist5(8, 1);
+
+// Explicit double precision:
+negative_binomial_distribution<double>        mydist6(8., 0.25);
+
+// Explicit long double precision:
+negative_binomial_distribution<long double>   mydist7(8., 0.25);
+
+

+ And you can use your own RealType, for example, boost::math::cpp_dec_float_50 + (an arbitrary 50 decimal digits precision type), then we can write: +

+
 using namespace boost::multiprecision;
+
+ negative_binomial_distribution<cpp_dec_float_50>  mydist8(8, 0.25);
+ // `integer` arguments are promoted to your RealType exactly, but
+ // `double` argument are converted to RealType,
+ // possibly losing precision, so don't write:
+
+ negative_binomial_distribution<cpp_dec_float_50>  mydist20(8, 0.23456789012345678901234567890);
+// to avoid truncation of second parameter to `0.2345678901234567`.
+
+ negative_binomial_distribution<cpp_dec_float_50>  mydist21(8, cpp_dec_float_50("0.23456789012345678901234567890") );
+
+ // Ensure that all potentially significant digits are shown.
+ std::cout.precision(std::numeric_limits<cpp_dec_float_50>::digits10);
+ cpp_dec_float_50 x("1.23456789012345678901234567890");
+ std::cout << pdf(mydist8, x) << std::endl;
+
+
showing  0.00012630010495970320103876754721976419438231705359935
+
+
+ + + + + +
[Warning]Warning

+ When using multiprecision, it is all too easy to get accidental truncation! +

+

+ For example, if you write +

+
std::cout << pdf(mydist8, 1.23456789012345678901234567890) << std::endl;
+
+

+ showing 0.00012630010495970318465064569310967179576805651692929, which + is wrong at about the 17th decimal digit! +

+

+ This is because the value provided is truncated to a double, + effectively double x + = 1.23456789012345678901234567890; +

+

+ Then the now double x + is passed to function pdf, + and this truncated double + value is finally promoted to cpp_dec_float_50. +

+

+ Another way of quietly getting the wrong answer is to write: +

+
std::cout << pdf(mydist8, cpp_dec_float_50(1.23456789012345678901234567890)) << std::endl;
+
+

+ A correct way from a multi-digit string value is +

+
std::cout << pdf(mydist8, cpp_dec_float_50("1.23456789012345678901234567890")) << std::endl;
+
+
+ + + + + +
[Tip]Tip

+ Getting about 17 decimal digits followed by many zeros is often a sign + of accidental truncation. +

+
+ + Default + arguments to distribution constructors. +
+

+ Note that default constructor arguments are only provided for some distributions. + So if you wrongly assume a default argument, you will get an error message, + for example: +

+
negative_binomial_distribution<> mydist8;
+
+
error C2512 no appropriate default constructor available.
+

+ No default constructors are provided for the negative + binomial distribution, because + it is difficult to chose any sensible default values for this distribution. +

+

+ For other distributions, like the normal distribution, it is obviously + very useful to provide 'standard' defaults for the mean (zero) and standard + deviation (unity) thus: +

+
normal_distribution(RealType mean = 0, RealType sd = 1);
+
+

+ So in this case we can write: +

+
  using boost::math::normal;
+
+  normal norm1;       // Standard normal distribution.
+  normal norm2(2);    // Mean = 2, std deviation = 1.
+  normal norm3(2, 3); // Mean = 2, std deviation = 3.
+
+  }
+  catch(std::exception &ex)
+  {
+    std::cout << ex.what() << std::endl;
+  }
+
+  return 0;
+}  // int main()
+
+

+ There is no useful output from this demonstration program, of course. +

+

+ See distribution_construction.cpp + for full source code. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/error_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/error_eg.html new file mode 100644 index 00000000..c2fb76bd --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/error_eg.html @@ -0,0 +1,206 @@ + + + +Error Handling Example + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ See error handling documentation + for a detailed explanation of the mechanism of handling errors, including + the common "bad" arguments to distributions and functions, and + how to use Policies to control it. +

+

+ But, by default, exceptions will be raised, + for domain errors, pole errors, numeric overflow, and internal evaluation + errors. To avoid the exceptions from getting thrown and instead get an + appropriate value returned, usually a NaN (domain errors pole errors or + internal errors), or infinity (from overflow), you need to change the policy. +

+

+ The following example demonstrates the effect of setting the macro BOOST_MATH_DOMAIN_ERROR_POLICY + when an invalid argument is encountered. For the purposes of this example, + we'll pass a negative degrees of freedom parameter to the student's t distribution. +

+

+ Since we know that this is a single file program we could just add: +

+
#define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error
+
+

+ to the top of the source file to change the default policy to one that + simply returns a NaN when a domain error occurs. Alternatively we could + use: +

+
#define BOOST_MATH_DOMAIN_ERROR_POLICY errno_on_error
+
+

+ To ensure the ::errno + is set when a domain error occurs as well as returning a NaN. +

+

+ This is safe provided the program consists of a single translation unit + and we place the define before + any #includes. Note that should we add the define after the includes then + it will have no effect! A warning such as: +

+
warning C4005: 'BOOST_MATH_OVERFLOW_ERROR_POLICY' : macro redefinition
+

+ is a certain sign that it will not have the desired + effect. +

+

+ We'll begin our sample program with the needed includes: +

+
   #define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error
+
+// Boost
+#include <boost/math/distributions/students_t.hpp>
+   using boost::math::students_t;  // Probability of students_t(df, t).
+
+// std
+#include <iostream>
+   using std::cout;
+   using std::endl;
+
+#include <stdexcept>
+
+
+#include <cstddef>
+   // using ::errno
+
+

+ Next we'll define the program's main() to call the student's t distribution + with an invalid degrees of freedom parameter, the program is set up to + handle either an exception or a NaN: +

+
int main()
+{
+   cout << "Example error handling using Student's t function. " << endl;
+   cout << "BOOST_MATH_DOMAIN_ERROR_POLICY is set to: "
+      << BOOST_STRINGIZE(BOOST_MATH_DOMAIN_ERROR_POLICY) << endl;
+
+   double degrees_of_freedom = -1; // A bad argument!
+   double t = 10;
+
+   try
+   {
+      errno = 0; // Clear/reset.
+      students_t dist(degrees_of_freedom); // exception is thrown here if enabled.
+      double p = cdf(dist, t);
+      // Test for error reported by other means:
+      if((boost::math::isnan)(p))
+      {
+         cout << "cdf returned a NaN!" << endl;
+         if (errno != 0)
+         { // So errno has been set.
+           cout << "errno is set to: " << errno << endl;
+         }
+      }
+      else
+         cout << "Probability of Student's t is " << p << endl;
+   }
+   catch(const std::exception& e)
+   {
+      std::cout <<
+         "\n""Message from thrown exception was:\n   " << e.what() << std::endl;
+   }
+   return 0;
+} // int main()
+
+

+ Here's what the program output looks like with a default build (one that + does throw exceptions): +

+
Example error handling using Student's t function.
+BOOST_MATH_DOMAIN_ERROR_POLICY is set to: throw_on_error
+
+Message from thrown exception was:
+   Error in function boost::math::students_t_distribution<double>::students_t_distribution:
+   Degrees of freedom argument is -1, but must be > 0 !
+
+

+ Alternatively let's build with: +

+
#define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error
+
+

+ Now the program output is: +

+
Example error handling using Student's t function.
+BOOST_MATH_DOMAIN_ERROR_POLICY is set to: ignore_error
+cdf returned a NaN!
+
+

+ And finally let's build with: +

+
#define BOOST_MATH_DOMAIN_ERROR_POLICY errno_on_error
+
+

+ Which gives the output show errno: +

+
Example error handling using Student's t function.
+BOOST_MATH_DOMAIN_ERROR_POLICY is set to: errno_on_error
+cdf returned a NaN!
+errno is set to: 33
+
+
+ + + + + +
[Caution]Caution
+

+ If throwing of exceptions is enabled (the default) but you do not have try & catch block, then the program + will terminate with an uncaught exception and probably abort. +

+

+ Therefore to get the benefit of helpful error messages, enabling all exceptions and using try & catch is recommended + for most applications. +

+

+ However, for simplicity, the is not done for most examples. +

+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/f_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/f_eg.html new file mode 100644 index 00000000..73e26829 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/f_eg.html @@ -0,0 +1,329 @@ + + + +F Distribution Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Imagine that you want to compare the standard deviations of two sample + to determine if they differ in any significant way, in this situation you + use the F distribution and perform an F-test. This situation commonly occurs + when conducting a process change comparison: "is a new process more + consistent that the old one?". +

+

+ In this example we'll be using the data for ceramic strength from http://www.itl.nist.gov/div898/handbook/eda/section4/eda42a1.htm. + The data for this case study were collected by Said Jahanmir of the NIST + Ceramics Division in 1996 in connection with a NIST/industry ceramics consortium + for strength optimization of ceramic strength. +

+

+ The example program is f_test.cpp, + program output has been deliberately made as similar as possible to the + DATAPLOT output in the corresponding NIST + EngineeringStatistics Handbook example. +

+

+ We'll begin by defining the procedure to conduct the test: +

+
void f_test(
+    double sd1,     // Sample 1 std deviation
+    double sd2,     // Sample 2 std deviation
+    double N1,      // Sample 1 size
+    double N2,      // Sample 2 size
+    double alpha)  // Significance level
+{
+
+

+ The procedure begins by printing out a summary of our input data: +

+
using namespace std;
+using namespace boost::math;
+
+// Print header:
+cout <<
+   "____________________________________\n"
+   "F test for equal standard deviations\n"
+   "____________________________________\n\n";
+cout << setprecision(5);
+cout << "Sample 1:\n";
+cout << setw(55) << left << "Number of Observations" << "=  " << N1 << "\n";
+cout << setw(55) << left << "Sample Standard Deviation" << "=  " << sd1 << "\n\n";
+cout << "Sample 2:\n";
+cout << setw(55) << left << "Number of Observations" << "=  " << N2 << "\n";
+cout << setw(55) << left << "Sample Standard Deviation" << "=  " << sd2 << "\n\n";
+
+

+ The test statistic for an F-test is simply the ratio of the square of the + two standard deviations: +

+

+ F = s12 / s22 +

+

+ where s1 is the standard deviation of the first sample and s2 +is the standard + deviation of the second sample. Or in code: +

+
double F = (sd1 / sd2);
+F *= F;
+cout << setw(55) << left << "Test Statistic" << "=  " << F << "\n\n";
+
+

+ At this point a word of caution: the F distribution is asymmetric, so we + have to be careful how we compute the tests, the following table summarises + the options available: +

+
++++ + + + + + + + + + + + + + + + + + + + + + + +
+

+ Hypothesis +

+
+

+ Test +

+
+

+ The null-hypothesis: there is no difference in standard deviations + (two sided test) +

+
+

+ Reject if F <= F(1-alpha/2; N1-1, N2-1) or F >= F(alpha/2; + N1-1, N2-1) +

+
+

+ The alternative hypothesis: there is a difference in means (two + sided test) +

+
+

+ Reject if F(1-alpha/2; N1-1, N2-1) <= F <= F(alpha/2; N1-1, + N2-1) +

+
+

+ The alternative hypothesis: Standard deviation of sample 1 is + greater than that of sample 2 +

+
+

+ Reject if F < F(alpha; N1-1, N2-1) +

+
+

+ The alternative hypothesis: Standard deviation of sample 1 is + less than that of sample 2 +

+
+

+ Reject if F > F(1-alpha; N1-1, N2-1) +

+
+

+ Where F(1-alpha; N1-1, N2-1) is the lower critical value of the F distribution + with degrees of freedom N1-1 and N2-1, and F(alpha; N1-1, N2-1) is the upper + critical value of the F distribution with degrees of freedom N1-1 and N2-1. +

+

+ The upper and lower critical values can be computed using the quantile + function: +

+

+ F(1-alpha; N1-1, N2-1) = quantile(fisher_f(N1-1, N2-1), + alpha) +

+

+ F(alpha; N1-1, N2-1) = quantile(complement(fisher_f(N1-1, N2-1), + alpha)) +

+

+ In our example program we need both upper and lower critical values for + alpha and for alpha/2: +

+
double ucv = quantile(complement(dist, alpha));
+double ucv2 = quantile(complement(dist, alpha / 2));
+double lcv = quantile(dist, alpha);
+double lcv2 = quantile(dist, alpha / 2);
+cout << setw(55) << left << "Upper Critical Value at alpha: " << "=  "
+   << setprecision(3) << scientific << ucv << "\n";
+cout << setw(55) << left << "Upper Critical Value at alpha/2: " << "=  "
+   << setprecision(3) << scientific << ucv2 << "\n";
+cout << setw(55) << left << "Lower Critical Value at alpha: " << "=  "
+   << setprecision(3) << scientific << lcv << "\n";
+cout << setw(55) << left << "Lower Critical Value at alpha/2: " << "=  "
+   << setprecision(3) << scientific << lcv2 << "\n\n";
+
+

+ The final step is to perform the comparisons given above, and print out + whether the hypothesis is rejected or not: +

+
cout << setw(55) << left <<
+   "Results for Alternative Hypothesis and alpha" << "=  "
+   << setprecision(4) << fixed << alpha << "\n\n";
+cout << "Alternative Hypothesis                                    Conclusion\n";
+
+cout << "Standard deviations are unequal (two sided test)          ";
+if((ucv2 < F) || (lcv2 > F))
+   cout << "ACCEPTED\n";
+else
+   cout << "REJECTED\n";
+
+cout << "Standard deviation 1 is less than standard deviation 2    ";
+if(lcv > F)
+   cout << "ACCEPTED\n";
+else
+   cout << "REJECTED\n";
+
+cout << "Standard deviation 1 is greater than standard deviation 2 ";
+if(ucv < F)
+   cout << "ACCEPTED\n";
+else
+   cout << "REJECTED\n";
+cout << endl << endl;
+
+

+ Using the ceramic strength data as an example we get the following output: +

+
F test for equal standard deviations
+____________________________________
+
+Sample 1:
+Number of Observations                                 =  240
+Sample Standard Deviation                              =  65.549
+
+Sample 2:
+Number of Observations                                 =  240
+Sample Standard Deviation                              =  61.854
+
+Test Statistic                                         =  1.123
+
+CDF of test statistic:                                 =  8.148e-001
+Upper Critical Value at alpha:                         =  1.238e+000
+Upper Critical Value at alpha/2:                       =  1.289e+000
+Lower Critical Value at alpha:                         =  8.080e-001
+Lower Critical Value at alpha/2:                       =  7.756e-001
+
+Results for Alternative Hypothesis and alpha           =  0.0500
+
+Alternative Hypothesis                                    Conclusion
+Standard deviations are unequal (two sided test)          REJECTED
+Standard deviation 1 is less than standard deviation 2    REJECTED
+Standard deviation 1 is greater than standard deviation 2 REJECTED
+
+

+ In this case we are unable to reject the null-hypothesis, and must instead + reject the alternative hypothesis. +

+

+ By contrast let's see what happens when we use some different sample + data:, once again from the NIST Engineering Statistics Handbook: + A new procedure to assemble a device is introduced and tested for possible + improvement in time of assembly. The question being addressed is whether + the standard deviation of the new assembly process (sample 2) is better + (i.e., smaller) than the standard deviation for the old assembly process + (sample 1). +

+
____________________________________
+F test for equal standard deviations
+____________________________________
+
+Sample 1:
+Number of Observations                                 =  11.00000
+Sample Standard Deviation                              =  4.90820
+
+Sample 2:
+Number of Observations                                 =  9.00000
+Sample Standard Deviation                              =  2.58740
+
+Test Statistic                                         =  3.59847
+
+CDF of test statistic:                                 =  9.589e-001
+Upper Critical Value at alpha:                         =  3.347e+000
+Upper Critical Value at alpha/2:                       =  4.295e+000
+Lower Critical Value at alpha:                         =  3.256e-001
+Lower Critical Value at alpha/2:                       =  2.594e-001
+
+Results for Alternative Hypothesis and alpha           =  0.0500
+
+Alternative Hypothesis                                    Conclusion
+Standard deviations are unequal (two sided test)          REJECTED
+Standard deviation 1 is less than standard deviation 2    REJECTED
+Standard deviation 1 is greater than standard deviation 2 ACCEPTED
+
+

+ In this case we take our null hypothesis as "standard deviation 1 + is less than or equal to standard deviation 2", since this represents + the "no change" situation. So we want to compare the upper critical + value at alpha (a one sided test) with the test statistic, + and since 3.35 < 3.6 this hypothesis must be rejected. We therefore + conclude that there is a change for the better in our standard deviation. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg.html new file mode 100644 index 00000000..0a292557 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg.html @@ -0,0 +1,55 @@ + + + +Find Location and Scale Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ + +
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_location_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_location_eg.html new file mode 100644 index 00000000..6a326882 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_location_eg.html @@ -0,0 +1,190 @@ + + + +Find Location (Mean) Example + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ First we need some includes to access the normal distribution, the algorithms + to find location (and some std output of course). +

+
#include <boost/math/distributions/normal.hpp> // for normal_distribution
+  using boost::math::normal; // typedef provides default type is double.
+#include <boost/math/distributions/cauchy.hpp> // for cauchy_distribution
+  using boost::math::cauchy; // typedef provides default type is double.
+#include <boost/math/distributions/find_location.hpp>
+  using boost::math::find_location; // for mean
+#include <boost/math/distributions/find_scale.hpp>
+  using boost::math::find_scale; // for standard devation
+  using boost::math::complement; // Needed if you want to use the complement version.
+  using boost::math::policies::policy;
+
+#include <iostream>
+  using std::cout; using std::endl;
+#include <iomanip>
+  using std::setw; using std::setprecision;
+#include <limits>
+  using std::numeric_limits;
+
+

+ For this example, we will use the standard normal distribution, with + mean (location) zero and standard deviation (scale) unity. This is also + the default for this implementation. +

+
normal N01;  // Default 'standard' normal distribution with zero mean and
+double sd = 1.; // normal default standard deviation is 1.
+
+

+ Suppose we want to find a different normal distribution whose mean is + shifted so that only fraction p (here 0.001 or 0.1%) are below a certain + chosen limit (here -2, two standard deviations). +

+
double z = -2.; // z to give prob p
+double p = 0.001; // only 0.1% below z
+
+cout << "Normal distribution with mean = " << N01.location()
+  << ", standard deviation " << N01.scale()
+  << ", has " << "fraction <= " << z
+  << ", p = "  << cdf(N01, z) << endl;
+cout << "Normal distribution with mean = " << N01.location()
+  << ", standard deviation " << N01.scale()
+  << ", has " << "fraction > " << z
+  << ", p = "  << cdf(complement(N01, z)) << endl; // Note: uses complement.
+
+
Normal distribution with mean = 0, standard deviation 1, has fraction <= -2, p = 0.0227501
+Normal distribution with mean = 0, standard deviation 1, has fraction > -2, p = 0.97725
+
+

+ We can now use ''find_location'' to give a new offset mean. +

+
double l = find_location<normal>(z, p, sd);
+cout << "offset location (mean) = " << l << endl;
+
+

+ that outputs: +

+
offset location (mean) = 1.09023
+
+

+ showing that we need to shift the mean just over one standard deviation + from its previous value of zero. +

+

+ Then we can check that we have achieved our objective by constructing + a new distribution with the offset mean (but same standard deviation): +

+
normal np001pc(l, sd); // Same standard_deviation (scale) but with mean (location) shifted.
+
+

+ And re-calculating the fraction below our chosen limit. +

+
cout << "Normal distribution with mean = " << l
+    << " has " << "fraction <= " << z
+    << ", p = "  << cdf(np001pc, z) << endl;
+  cout << "Normal distribution with mean = " << l
+    << " has " << "fraction > " << z
+    << ", p = "  << cdf(complement(np001pc, z)) << endl;
+
+
Normal distribution with mean = 1.09023 has fraction <= -2, p = 0.001
+Normal distribution with mean = 1.09023 has fraction > -2, p = 0.999
+
+
+ + Controlling + Error Handling from find_location +
+

+ We can also control the policy for handling various errors. For example, + we can define a new (possibly unwise) policy to ignore domain errors + ('bad' arguments). +

+

+ Unless we are using the boost::math namespace, we will need: +

+
using boost::math::policies::policy;
+using boost::math::policies::domain_error;
+using boost::math::policies::ignore_error;
+
+

+ Using a typedef is often convenient, especially if it is re-used, although + it is not required, as the various examples below show. +

+
typedef policy<domain_error<ignore_error> > ignore_domain_policy;
+// find_location with new policy, using typedef.
+l = find_location<normal>(z, p, sd, ignore_domain_policy());
+// Default policy policy<>, needs "using boost::math::policies::policy;"
+l = find_location<normal>(z, p, sd, policy<>());
+// Default policy, fully specified.
+l = find_location<normal>(z, p, sd, boost::math::policies::policy<>());
+// A new policy, ignoring domain errors, without using a typedef.
+l = find_location<normal>(z, p, sd, policy<domain_error<ignore_error> >());
+
+

+ If we want to use a probability that is the complements + of our probability, we should not even think of writing find_location<normal>(z, 1 - p, sd), but use the complement version, see + why complements?. +

+
z = 2.;
+double q = 0.95; // = 1 - p; // complement.
+l = find_location<normal>(complement(z, q, sd));
+
+normal np95pc(l, sd); // Same standard_deviation (scale) but with mean(location) shifted
+cout << "Normal distribution with mean = " << l << " has "
+  << "fraction <= " << z << " = "  << cdf(np95pc, z) << endl;
+cout << "Normal distribution with mean = " << l << " has "
+  << "fraction > " << z << " = "  << cdf(complement(np95pc, z)) << endl;
+
+

+ See find_location_example.cpp + for full source code: the program output looks like this: +

+
Example: Find location (mean).
+Normal distribution with mean = 0, standard deviation 1, has fraction <= -2, p = 0.0227501
+Normal distribution with mean = 0, standard deviation 1, has fraction > -2, p = 0.97725
+offset location (mean) = 1.09023
+Normal distribution with mean = 1.09023 has fraction <= -2, p = 0.001
+Normal distribution with mean = 1.09023 has fraction > -2, p = 0.999
+Normal distribution with mean = 0.355146 has fraction <= 2 = 0.95
+Normal distribution with mean = 0.355146 has fraction > 2 = 0.05
+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_mean_and_sd_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_mean_and_sd_eg.html new file mode 100644 index 00000000..7e2f93d3 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_mean_and_sd_eg.html @@ -0,0 +1,455 @@ + + + +Find mean and standard deviation example + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ First we need some includes to access the normal distribution, the algorithms + to find location and scale (and some std output of course). +

+
#include <boost/math/distributions/normal.hpp> // for normal_distribution
+  using boost::math::normal; // typedef provides default type is double.
+#include <boost/math/distributions/cauchy.hpp> // for cauchy_distribution
+  using boost::math::cauchy; // typedef provides default type is double.
+#include <boost/math/distributions/find_location.hpp>
+  using boost::math::find_location;
+#include <boost/math/distributions/find_scale.hpp>
+  using boost::math::find_scale;
+  using boost::math::complement;
+  using boost::math::policies::policy;
+
+#include <iostream>
+  using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;
+#include <iomanip>
+  using std::setw; using std::setprecision;
+#include <limits>
+  using std::numeric_limits;
+#include <stdexcept>
+
+
+ + Using + find_location and find_scale to meet dispensing and measurement specifications +
+

+ Consider an example from K Krishnamoorthy, Handbook of Statistical Distributions + with Applications, ISBN 1-58488-635-8, (2006) p 126, example 10.3.7. +

+

+ "A machine is set to pack 3 kg of ground beef per pack. Over a long + period of time it is found that the average packed was 3 kg with a standard + deviation of 0.1 kg. Assume the packing is normally distributed." +

+

+ We start by constructing a normal distribution with the given parameters: +

+
double mean = 3.; // kg
+double standard_deviation = 0.1; // kg
+normal packs(mean, standard_deviation);
+
+

+ We can then find the fraction (or %) of packages that weigh more than + 3.1 kg. +

+
double max_weight = 3.1; // kg
+cout << "Percentage of packs > " << max_weight << " is "
+<< cdf(complement(packs, max_weight)) * 100. << endl; // P(X > 3.1)
+
+

+ We might want to ensure that 95% of packs are over a minimum weight specification, + then we want the value of the mean such that P(X < 2.9) = 0.05. +

+

+ Using the mean of 3 kg, we can estimate the fraction of packs that fail + to meet the specification of 2.9 kg. +

+
double minimum_weight = 2.9;
+cout <<"Fraction of packs <= " << minimum_weight << " with a mean of " << mean
+  << " is " << cdf(complement(packs, minimum_weight)) << endl;
+// fraction of packs <= 2.9 with a mean of 3 is 0.841345
+
+

+ This is 0.84 - more than the target fraction of 0.95. If we want 95% + to be over the minimum weight, what should we set the mean weight to + be? +

+

+ Using the KK StatCalc program supplied with the book and the method given + on page 126 gives 3.06449. +

+

+ We can confirm this by constructing a new distribution which we call + 'xpacks' with a safety margin mean of 3.06449 thus: +

+
double over_mean = 3.06449;
+normal xpacks(over_mean, standard_deviation);
+cout << "Fraction of packs >= " << minimum_weight
+<< " with a mean of " << xpacks.mean()
+  << " is " << cdf(complement(xpacks, minimum_weight)) << endl;
+// fraction of packs >= 2.9 with a mean of 3.06449 is 0.950005
+
+

+ Using this Math Toolkit, we can calculate the required mean directly + thus: +

+
double under_fraction = 0.05;  // so 95% are above the minimum weight mean - sd = 2.9
+double low_limit = standard_deviation;
+double offset = mean - low_limit - quantile(packs, under_fraction);
+double nominal_mean = mean + offset;
+// mean + (mean - low_limit - quantile(packs, under_fraction));
+
+normal nominal_packs(nominal_mean, standard_deviation);
+cout << "Setting the packer to " << nominal_mean << " will mean that "
+  << "fraction of packs >= " << minimum_weight
+  << " is " << cdf(complement(nominal_packs, minimum_weight)) << endl;
+// Setting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95
+
+

+ This calculation is generalized as the free function called find_location, see algorithms. +

+

+ To use this we will need to +

+
#include <boost/math/distributions/find_location.hpp>
+  using boost::math::find_location;
+
+

+ and then use find_location function to find safe_mean, & construct + a new normal distribution called 'goodpacks'. +

+
double safe_mean = find_location<normal>(minimum_weight, under_fraction, standard_deviation);
+normal good_packs(safe_mean, standard_deviation);
+
+

+ with the same confirmation as before: +

+
cout << "Setting the packer to " << nominal_mean << " will mean that "
+  << "fraction of packs >= " << minimum_weight
+  << " is " << cdf(complement(good_packs, minimum_weight)) << endl;
+// Setting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95
+
+
+ + Using + Cauchy-Lorentz instead of normal distribution +
+

+ After examining the weight distribution of a large number of packs, we + might decide that, after all, the assumption of a normal distribution + is not really justified. We might find that the fit is better to a Cauchy Distribution. + This distribution has wider 'wings', so that whereas most of the values + are closer to the mean than the normal, there are also more values than + 'normal' that lie further from the mean than the normal. +

+

+ This might happen because a larger than normal lump of meat is either + included or excluded. +

+

+ We first create a Cauchy + Distribution with the original mean and standard deviation, and + estimate the fraction that lie below our minimum weight specification. +

+
cauchy cpacks(mean, standard_deviation);
+cout << "Cauchy Setting the packer to " << mean << " will mean that "
+  << "fraction of packs >= " << minimum_weight
+  << " is " << cdf(complement(cpacks, minimum_weight)) << endl;
+// Cauchy Setting the packer to 3 will mean that fraction of packs >= 2.9 is 0.75
+
+

+ Note that far fewer of the packs meet the specification, only 75% instead + of 95%. Now we can repeat the find_location, using the cauchy distribution + as template parameter, in place of the normal used above. +

+
double lc = find_location<cauchy>(minimum_weight, under_fraction, standard_deviation);
+cout << "find_location<cauchy>(minimum_weight, over fraction, standard_deviation); " << lc << endl;
+// find_location<cauchy>(minimum_weight, over fraction, packs.standard_deviation()); 3.53138
+
+

+ Note that the safe_mean setting needs to be much higher, 3.53138 instead + of 3.06449, so we will make rather less profit. +

+

+ And again confirm that the fraction meeting specification is as expected. +

+
cauchy goodcpacks(lc, standard_deviation);
+cout << "Cauchy Setting the packer to " << lc << " will mean that "
+  << "fraction of packs >= " << minimum_weight
+  << " is " << cdf(complement(goodcpacks, minimum_weight)) << endl;
+// Cauchy Setting the packer to 3.53138 will mean that fraction of packs >= 2.9 is 0.95
+
+

+ Finally we could estimate the effect of a much tighter specification, + that 99% of packs met the specification. +

+
cout << "Cauchy Setting the packer to "
+  << find_location<cauchy>(minimum_weight, 0.99, standard_deviation)
+  << " will mean that "
+  << "fraction of packs >= " << minimum_weight
+  << " is " << cdf(complement(goodcpacks, minimum_weight)) << endl;
+
+

+ Setting the packer to 3.13263 will mean that fraction of packs >= + 2.9 is 0.99, but will more than double the mean loss from 0.0644 to 0.133 + kg per pack. +

+

+ Of course, this calculation is not limited to packs of meat, it applies + to dispensing anything, and it also applies to a 'virtual' material like + any measurement. +

+

+ The only caveat is that the calculation assumes that the standard deviation + (scale) is known with a reasonably low uncertainty, something that is + not so easy to ensure in practice. And that the distribution is well + defined, Normal + Distribution or Cauchy + Distribution, or some other. +

+

+ If one is simply dispensing a very large number of packs, then it may + be feasible to measure the weight of hundreds or thousands of packs. + With a healthy 'degrees of freedom', the confidence intervals for the + standard deviation are not too wide, typically about + and - 10% for + hundreds of observations. +

+

+ For other applications, where it is more difficult or expensive to make + many observations, the confidence intervals are depressingly wide. +

+

+ See Confidence + Intervals on the standard deviation for a worked example chi_square_std_dev_test.cpp + of estimating these intervals. +

+
+ + Changing + the scale or standard deviation +
+

+ Alternatively, we could invest in a better (more precise) packer (or + measuring device) with a lower standard deviation, or scale. +

+

+ This might cost more, but would reduce the amount we have to 'give away' + in order to meet the specification. +

+

+ To estimate how much better (how much smaller standard deviation) it + would have to be, we need to get the 5% quantile to be located at the + under_weight limit, 2.9 +

+
double p = 0.05; // wanted p th quantile.
+cout << "Quantile of " << p << " = " << quantile(packs, p)
+  << ", mean = " << packs.mean() << ", sd = " << packs.standard_deviation() << endl;
+
+

+ Quantile of 0.05 = 2.83551, mean = 3, sd = 0.1 +

+

+ With the current packer (mean = 3, sd = 0.1), the 5% quantile is at 2.8551 + kg, a little below our target of 2.9 kg. So we know that the standard + deviation is going to have to be smaller. +

+

+ Let's start by guessing that it (now 0.1) needs to be halved, to a standard + deviation of 0.05 kg. +

+
normal pack05(mean, 0.05);
+cout << "Quantile of " << p << " = " << quantile(pack05, p)
+  << ", mean = " << pack05.mean() << ", sd = " << pack05.standard_deviation() << endl;
+// Quantile of 0.05 = 2.91776, mean = 3, sd = 0.05
+
+cout <<"Fraction of packs >= " << minimum_weight << " with a mean of " << mean
+  << " and standard deviation of " << pack05.standard_deviation()
+  << " is " << cdf(complement(pack05, minimum_weight)) << endl;
+// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.05 is 0.97725
+
+

+ So 0.05 was quite a good guess, but we are a little over the 2.9 target, + so the standard deviation could be a tiny bit more. So we could do some + more guessing to get closer, say by increasing standard deviation to + 0.06 kg, constructing another new distribution called pack06. +

+
normal pack06(mean, 0.06);
+cout << "Quantile of " << p << " = " << quantile(pack06, p)
+  << ", mean = " << pack06.mean() << ", sd = " << pack06.standard_deviation() << endl;
+// Quantile of 0.05 = 2.90131, mean = 3, sd = 0.06
+
+cout <<"Fraction of packs >= " << minimum_weight << " with a mean of " << mean
+  << " and standard deviation of " << pack06.standard_deviation()
+  << " is " << cdf(complement(pack06, minimum_weight)) << endl;
+// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.06 is 0.95221
+
+

+ Now we are getting really close, but to do the job properly, we might + need to use root finding method, for example the tools provided, and + used elsewhere, in the Math Toolkit, see root-finding + without derivatives +

+

+ But in this (normal) distribution case, we can and should be even smarter + and make a direct calculation. +

+

+ Our required limit is minimum_weight = 2.9 kg, often called the random + variate z. For a standard normal distribution, then probability p = N((minimum_weight + - mean) / sd). +

+

+ We want to find the standard deviation that would be required to meet + this limit, so that the p th quantile is located at z (minimum_weight). + In this case, the 0.05 (5%) quantile is at 2.9 kg pack weight, when the + mean is 3 kg, ensuring that 0.95 (95%) of packs are above the minimum + weight. +

+

+ Rearranging, we can directly calculate the required standard deviation: +

+
normal N01; // standard normal distribution with mean zero and unit standard deviation.
+p = 0.05;
+double qp = quantile(N01, p);
+double sd95 = (minimum_weight - mean) / qp;
+
+cout << "For the "<< p << "th quantile to be located at "
+  << minimum_weight << ", would need a standard deviation of " << sd95 << endl;
+// For the 0.05th quantile to be located at 2.9, would need a standard deviation of 0.0607957
+
+

+ We can now construct a new (normal) distribution pack95 for the 'better' + packer, and check that our distribution will meet the specification. +

+
normal pack95(mean, sd95);
+cout <<"Fraction of packs >= " << minimum_weight << " with a mean of " << mean
+  << " and standard deviation of " << pack95.standard_deviation()
+  << " is " << cdf(complement(pack95, minimum_weight)) << endl;
+// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95
+
+

+ This calculation is generalized in the free function find_scale, as shown + below, giving the same standard deviation. +

+
double ss = find_scale<normal>(minimum_weight, under_fraction, packs.mean());
+cout << "find_scale<normal>(minimum_weight, under_fraction, packs.mean()); " << ss << endl;
+// find_scale<normal>(minimum_weight, under_fraction, packs.mean()); 0.0607957
+
+

+ If we had defined an over_fraction, or percentage that must pass specification +

+
double over_fraction = 0.95;
+
+

+ And (wrongly) written +

+
double sso = find_scale<normal>(minimum_weight, over_fraction, packs.mean());
+
+

+ With the default policy, we would get a message like +

+
Message from thrown exception was:
+   Error in function boost::math::find_scale<Dist, Policy>(double, double, double, Policy):
+   Computed scale (-0.060795683191176959) is <= 0! Was the complement intended?
+
+

+ But this would return a negative standard + deviation - obviously impossible. The probability should be 1 - over_fraction, + not over_fraction, thus: +

+
double ss1o = find_scale<normal>(minimum_weight, 1 - over_fraction, packs.mean());
+cout << "find_scale<normal>(minimum_weight, under_fraction, packs.mean()); " << ss1o << endl;
+// find_scale<normal>(minimum_weight, under_fraction, packs.mean()); 0.0607957
+
+

+ But notice that using '1 - over_fraction' - will lead to a loss of accuracy, + especially if over_fraction was close to unity. (See why + complements?). In this (very common) case, we should instead use + the complements, + giving the most accurate result. +

+
double ssc = find_scale<normal>(complement(minimum_weight, over_fraction, packs.mean()));
+cout << "find_scale<normal>(complement(minimum_weight, over_fraction, packs.mean())); " << ssc << endl;
+// find_scale<normal>(complement(minimum_weight, over_fraction, packs.mean())); 0.0607957
+
+

+ Note that our guess of 0.06 was close to the accurate value of 0.060795683191176959. +

+

+ We can again confirm our prediction thus: +

+
normal pack95c(mean, ssc);
+cout <<"Fraction of packs >= " << minimum_weight << " with a mean of " << mean
+  << " and standard deviation of " << pack95c.standard_deviation()
+  << " is " << cdf(complement(pack95c, minimum_weight)) << endl;
+// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95
+
+

+ Notice that these two deceptively simple questions: +

+
  • + Do we over-fill to make sure we meet a minimum specification (or + under-fill to avoid an overdose)? +
+

+ and/or +

+
  • + Do we measure better? +
+

+ are actually extremely common. +

+

+ The weight of beef might be replaced by a measurement of more or less + anything, from drug tablet content, Apollo landing rocket firing, X-ray + treatment doses... +

+

+ The scale can be variation in dispensing or uncertainty in measurement. +

+

+ See find_mean_and_sd_normal.cpp + for full source code & appended program output. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_scale_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_scale_eg.html new file mode 100644 index 00000000..82fd9a14 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/find_eg/find_scale_eg.html @@ -0,0 +1,209 @@ + + + +Find Scale (Standard Deviation) Example + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ First we need some includes to access the Normal + Distribution, the algorithms to find scale (and some std output + of course). +

+
#include <boost/math/distributions/normal.hpp> // for normal_distribution
+  using boost::math::normal; // typedef provides default type is double.
+#include <boost/math/distributions/find_scale.hpp>
+  using boost::math::find_scale;
+  using boost::math::complement; // Needed if you want to use the complement version.
+  using boost::math::policies::policy; // Needed to specify the error handling policy.
+
+#include <iostream>
+  using std::cout; using std::endl;
+#include <iomanip>
+  using std::setw; using std::setprecision;
+#include <limits>
+  using std::numeric_limits;
+
+

+ For this example, we will use the standard Normal + Distribution, with location (mean) zero and standard deviation + (scale) unity. Conveniently, this is also the default for this implementation's + constructor. +

+
normal N01;  // Default 'standard' normal distribution with zero mean
+double sd = 1.; // and standard deviation is 1.
+
+

+ Suppose we want to find a different normal distribution with standard + deviation so that only fraction p (here 0.001 or 0.1%) are below a certain + chosen limit (here -2. standard deviations). +

+
double z = -2.; // z to give prob p
+double p = 0.001; // only 0.1% below z = -2
+
+cout << "Normal distribution with mean = " << N01.location()  // aka N01.mean()
+  << ", standard deviation " << N01.scale() // aka N01.standard_deviation()
+  << ", has " << "fraction <= " << z
+  << ", p = "  << cdf(N01, z) << endl;
+cout << "Normal distribution with mean = " << N01.location()
+  << ", standard deviation " << N01.scale()
+  << ", has " << "fraction > " << z
+  << ", p = "  << cdf(complement(N01, z)) << endl; // Note: uses complement.
+
+
Normal distribution with mean = 0 has fraction <= -2, p = 0.0227501
+Normal distribution with mean = 0 has fraction > -2, p = 0.97725
+
+

+ Noting that p = 0.02 instead of our target of 0.001, we can now use + find_scale to give a + new standard deviation. +

+
double l = N01.location();
+double s = find_scale<normal>(z, p, l);
+cout << "scale (standard deviation) = " << s << endl;
+
+

+ that outputs: +

+
scale (standard deviation) = 0.647201
+
+

+ showing that we need to reduce the standard deviation from 1. to 0.65. +

+

+ Then we can check that we have achieved our objective by constructing + a new distribution with the new standard deviation (but same zero mean): +

+
normal np001pc(N01.location(), s);
+
+

+ And re-calculating the fraction below (and above) our chosen limit. +

+
cout << "Normal distribution with mean = " << l
+  << " has " << "fraction <= " << z
+  << ", p = "  << cdf(np001pc, z) << endl;
+cout << "Normal distribution with mean = " << l
+  << " has " << "fraction > " << z
+  << ", p = "  << cdf(complement(np001pc, z)) << endl;
+
+
Normal distribution with mean = 0 has fraction <= -2, p = 0.001
+Normal distribution with mean = 0 has fraction > -2, p = 0.999
+
+
+ + Controlling + how Errors from find_scale are handled +
+

+ We can also control the policy for handling various errors. For example, + we can define a new (possibly unwise) policy to ignore domain errors + ('bad' arguments). +

+

+ Unless we are using the boost::math namespace, we will need: +

+
using boost::math::policies::policy;
+using boost::math::policies::domain_error;
+using boost::math::policies::ignore_error;
+
+

+ Using a typedef is convenient, especially if it is re-used, although + it is not required, as the various examples below show. +

+
typedef policy<domain_error<ignore_error> > ignore_domain_policy;
+// find_scale with new policy, using typedef.
+l = find_scale<normal>(z, p, l, ignore_domain_policy());
+// Default policy policy<>, needs using boost::math::policies::policy;
+
+l = find_scale<normal>(z, p, l, policy<>());
+// Default policy, fully specified.
+l = find_scale<normal>(z, p, l, boost::math::policies::policy<>());
+// New policy, without typedef.
+l = find_scale<normal>(z, p, l, policy<domain_error<ignore_error> >());
+
+

+ If we want to express a probability, say 0.999, that is a complement, + 1 - + p we should not even think + of writing find_scale<normal>(z, 1 - + p, + l), + but use the complements + version (see why complements?). +

+
z = -2.;
+double q = 0.999; // = 1 - p; // complement of 0.001.
+sd = find_scale<normal>(complement(z, q, l));
+
+normal np95pc(l, sd); // Same standard_deviation (scale) but with mean(scale) shifted
+cout << "Normal distribution with mean = " << l << " has "
+  << "fraction <= " << z << " = "  << cdf(np95pc, z) << endl;
+cout << "Normal distribution with mean = " << l << " has "
+  << "fraction > " << z << " = "  << cdf(complement(np95pc, z)) << endl;
+
+

+ Sadly, it is all too easy to get probabilities the wrong way round, when + you may get a warning like this: +

+
Message from thrown exception was:
+   Error in function boost::math::find_scale<Dist, Policy>(complement(double, double, double, Policy)):
+   Computed scale (-0.48043523852179076) is <= 0! Was the complement intended?
+
+

+ The default error handling policy is to throw an exception with this + message, but if you chose a policy to ignore the error, the (impossible) + negative scale is quietly returned. +

+

+ See find_scale_example.cpp + for full source code: the program output looks like this: +

+
Example: Find scale (standard deviation).
+Normal distribution with mean = 0, standard deviation 1, has fraction <= -2, p = 0.0227501
+Normal distribution with mean = 0, standard deviation 1, has fraction > -2, p = 0.97725
+scale (standard deviation) = 0.647201
+Normal distribution with mean = 0 has fraction <= -2, p = 0.001
+Normal distribution with mean = 0 has fraction > -2, p = 0.999
+Normal distribution with mean = 0.946339 has fraction <= -2 = 0.001
+Normal distribution with mean = 0.946339 has fraction > -2 = 0.999
+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/geometric_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/geometric_eg.html new file mode 100644 index 00000000..da244826 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/geometric_eg.html @@ -0,0 +1,422 @@ + + + +Geometric Distribution Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ For this example, we will opt to #define two macros to control the error + and discrete handling policies. For this simple example, we want to avoid + throwing an exception (the default policy) and just return infinity. We + want to treat the distribution as if it was continuous, so we choose a + discrete_quantile policy of real, rather than the default policy integer_round_outwards. +

+
#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error
+#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real
+
+
+ + + + + +
[Caution]Caution

+ It is vital to #include distributions etc after + the above #defines +

+

+ After that we need some includes to provide easy access to the negative + binomial distribution, and we need some std library iostream, of course. +

+
#include <boost/math/distributions/geometric.hpp>
+  // for geometric_distribution
+  using ::boost::math::geometric_distribution; //
+  using ::boost::math::geometric; // typedef provides default type is double.
+  using  ::boost::math::pdf; // Probability mass function.
+  using  ::boost::math::cdf; // Cumulative density function.
+  using  ::boost::math::quantile;
+
+#include <boost/math/distributions/negative_binomial.hpp>
+  // for negative_binomial_distribution
+  using boost::math::negative_binomial; // typedef provides default type is double.
+
+#include <boost/math/distributions/normal.hpp>
+  // for negative_binomial_distribution
+  using boost::math::normal; // typedef provides default type is double.
+
+#include <iostream>
+  using std::cout; using std::endl;
+  using std::noshowpoint; using std::fixed; using std::right; using std::left;
+#include <iomanip>
+  using std::setprecision; using std::setw;
+
+#include <limits>
+  using std::numeric_limits;
+
+

+ It is always sensible to use try and catch blocks because defaults policies + are to throw an exception if anything goes wrong. +

+

+ Simple try'n'catch blocks (see below) will ensure that you get a helpful + error message instead of an abrupt (and silent) program abort. +

+
+ + Throwing + a dice +
+

+ The Geometric distribution describes the probability (p) + of a number of failures to get the first success in k + Bernoulli trials. (A Bernoulli + trial is one with only two possible outcomes, success of failure, + and p is the probability of success). +

+

+ Suppose an 'fair' 6-face dice is thrown repeatedly: +

+
double success_fraction = 1./6; // success_fraction (p) = 0.1666
+// (so failure_fraction is 1 - success_fraction = 5./6 = 1- 0.1666 = 0.8333)
+
+

+ If the dice is thrown repeatedly until the first + time a three appears. The probablility distribution + of the number of times it is thrown not + getting a three (not-a-threes + number of failures to get a three) is a geometric + distribution with the success_fraction = 1/6 = 0.1666 ̇. +

+

+ We therefore start by constructing a geometric distribution with the one + parameter success_fraction, the probability of success. +

+
geometric g6(success_fraction); // type double by default.
+
+

+ To confirm, we can echo the success_fraction parameter of the distribution. +

+
cout << "success fraction of a six-sided dice is " << g6.success_fraction() << endl;
+
+

+ So the probability of getting a three at the first throw (zero failures) + is +

+
cout << pdf(g6, 0) << endl; // 0.1667
+cout << cdf(g6, 0) << endl; // 0.1667
+
+

+ Note that the cdf and pdf are identical because the is only one throw. + If we want the probability of getting the first three + on the 2nd throw: +

+
cout << pdf(g6, 1) << endl; // 0.1389
+
+

+ If we want the probability of getting the first three + on the 1st or 2nd throw (allowing one failure): +

+
cout << "pdf(g6, 0) + pdf(g6, 1) = " << pdf(g6, 0) + pdf(g6, 1) << endl;
+
+

+ Or more conveniently, and more generally, we can use the Cumulative Distribution + Function CDF. +

+
cout << "cdf(g6, 1) = " << cdf(g6, 1) << endl; // 0.3056
+
+

+ If we allow many more (12) throws, the probability of getting our three + gets very high: +

+
cout << "cdf(g6, 12) = " << cdf(g6, 12) << endl; // 0.9065 or 90% probability.
+
+

+ If we want to be much more confident, say 99%, we can estimate the number + of throws to be this sure using the inverse or quantile. +

+
cout << "quantile(g6, 0.99) = " << quantile(g6, 0.99) << endl; // 24.26
+
+

+ Note that the value returned is not an integer: if you want an integer + result you should use either floor, round or ceil functions, or use the + policies mechanism. +

+

+ See understanding + discrete quantiles. +

+

+ The geometric distribution is related to the negative binomial    negative_binomial_distribution(RealType r, RealType + p); + with parameter r = 1. So we could get the same result + using the negative binomial, but using the geometric the results will be + faster, and may be more accurate. +

+
negative_binomial nb(1, success_fraction);
+cout << pdf(nb, 1) << endl; // 0.1389
+cout << cdf(nb, 1) << endl; // 0.3056
+
+

+ We could also the complement to express the required probability as 1 - + 0.99 = 0.01 (and get the same result): +

+
cout << "quantile(complement(g6, 1 - p))  " << quantile(complement(g6, 0.01)) << endl; // 24.26
+
+

+ Note too that Boost.Math geometric distribution is implemented as a continuous + function. Unlike other implementations (for example R) it uses + the number of failures as a real parameter, + not as an integer. If you want this integer behaviour, you may need to + enforce this by rounding the parameter you pass, probably rounding down, + to the nearest integer. For example, R returns the success fraction probability + for all values of failures from 0 to 0.999999 thus: +

+
   R> formatC(pgeom(0.0001,0.5, FALSE), digits=17) "               0.5"
+
+

+ So in Boost.Math the equivalent is +

+
    geometric g05(0.5);  // Probability of success = 0.5 or 50%
+    // Output all potentially significant digits for the type, here double.
+
+#ifdef BOOST_NO_CXX11_NUMERIC_LIMITS
+  int max_digits10 = 2 + (boost::math::policies::digits<double, boost::math::policies::policy<> >() * 30103UL) / 100000UL;
+  cout << "BOOST_NO_CXX11_NUMERIC_LIMITS is defined" << endl;
+#else
+  int max_digits10 = std::numeric_limits<double>::max_digits10;
+#endif
+  cout << "Show all potentially significant decimal digits std::numeric_limits<double>::max_digits10 = "
+    << max_digits10 << endl;
+  cout.precision(max_digits10); //
+
+    cout << cdf(g05, 0.0001) << endl; // returns 0.5000346561579232, not exact 0.5.
+
+

+ To get the R discrete behaviour, you simply need to round with, for example, + the floor function. +

+
cout << cdf(g05, floor(0.0001)) << endl; // returns exactly 0.5
+
+
> formatC(pgeom(0.9999999,0.5, FALSE), digits=17) [1] "              0.25"
+> formatC(pgeom(1.999999,0.5, FALSE), digits=17)[1] "              0.25" k = 1
+> formatC(pgeom(1.9999999,0.5, FALSE), digits=17)[1] "0.12500000000000003" k = 2
+
+

+ shows that R makes an arbitrary round-up decision at about 1e7 from the + next integer above. This may be convenient in practice, and could be replicated + in C++ if desired. +

+
+ + Surveying + customers to find one with a faulty product +
+

+ A company knows from warranty claims that 2% of their products will be + faulty, so the 'success_fraction' of finding a fault is 0.02. It wants + to interview a purchaser of faulty products to assess their 'user experience'. +

+

+ To estimate how many customers they will probably need to contact in order + to find one who has suffered from the fault, we first construct a geometric + distribution with probability 0.02, and then chose a confidence, say 80%, + 95%, or 99% to finding a customer with a fault. Finally, we probably want + to round up the result to the integer above using the ceil + function. (We could also use a policy, but that is hardly worthwhile for + this simple application.) +

+

+ (This also assumes that each customer only buys one product: if customers + bought more than one item, the probability of finding a customer with a + fault obviously improves.) +

+
cout.precision(5);
+geometric g(0.02); // On average, 2 in 100 products are faulty.
+double c = 0.95; // 95% confidence.
+cout << " quantile(g, " << c << ") = " << quantile(g, c) << endl;
+
+cout << "To be " << c * 100
+  << "% confident of finding we customer with a fault, need to survey "
+  <<  ceil(quantile(g, c)) << " customers." << endl; // 148
+c = 0.99; // Very confident.
+cout << "To be " << c * 100
+  << "% confident of finding we customer with a fault, need to survey "
+  <<  ceil(quantile(g, c)) << " customers." << endl; // 227
+c = 0.80; // Only reasonably confident.
+cout << "To be " << c * 100
+  << "% confident of finding we customer with a fault, need to survey "
+  <<  ceil(quantile(g, c)) << " customers." << endl; // 79
+
+
+ + Basket + Ball Shooters +
+

+ According to Wikipedia, average pro basket ball players get free + throws in the baskets 70 to 80 % of the time, but some get as high + as 95%, and others as low as 50%. Suppose we want to compare the probabilities + of failing to get a score only on the first or on the fifth shot? To start + we will consider the average shooter, say 75%. So we construct a geometric + distribution with success_fraction parameter 75/100 = 0.75. +

+
cout.precision(2);
+geometric gav(0.75); // Shooter averages 7.5 out of 10 in the basket.
+
+

+ What is probability of getting 1st try in the basket, that is with no failures? +

+
cout << "Probability of score on 1st try = " << pdf(gav, 0) << endl; // 0.75
+
+

+ This is, of course, the success_fraction probability 75%. What is the probability + that the shooter only scores on the fifth shot? So there are 5-1 = 4 failures + before the first success. +

+
cout << "Probability of score on 5th try = " << pdf(gav, 4) << endl; // 0.0029
+
+

+ Now compare this with the poor and the best players success fraction. We + need to constructing new distributions with the different success fractions, + and then get the corresponding probability density functions values: +

+
geometric gbest(0.95);
+cout << "Probability of score on 5th try = " << pdf(gbest, 4) << endl; // 5.9e-6
+geometric gmediocre(0.50);
+cout << "Probability of score on 5th try = " << pdf(gmediocre, 4) << endl; // 0.031
+
+

+ So we can see the very much smaller chance (0.000006) of 4 failures by + the best shooters, compared to the 0.03 of the mediocre. +

+
+ + Estimating + failures +
+

+ Of course one man's failure is an other man's success. So a fault can be + defined as a 'success'. +

+

+ If a fault occurs once after 100 flights, then one might naively say that + the risk of fault is obviously 1 in 100 = 1/100, a probability of 0.01. +

+

+ This is the best estimate we can make, but while it is the truth, it is + not the whole truth, for it hides the big uncertainty when estimating from + a single event. "One swallow doesn't make a summer." To show + the magnitude of the uncertainty, the geometric (or the negative binomial) + distribution can be used. +

+

+ If we chose the popular 95% confidence in the limits, corresponding to + an alpha of 0.05, because we are calculating a two-sided interval, we must + divide alpha by two. +

+
double alpha = 0.05;
+double k = 100; // So frequency of occurrence is 1/100.
+cout << "Probability is failure is " << 1/k << endl;
+double t = geometric::find_lower_bound_on_p(k, alpha/2);
+cout << "geometric::find_lower_bound_on_p(" << int(k) << ", " << alpha/2 << ") = "
+  << t << endl; // 0.00025
+t = geometric::find_upper_bound_on_p(k, alpha/2);
+cout << "geometric::find_upper_bound_on_p(" << int(k) << ", " << alpha/2 << ") = "
+  << t << endl; // 0.037
+
+

+ So while we estimate the probability is 0.01, it might lie between 0.0003 + and 0.04. Even if we relax our confidence to alpha = 90%, the bounds only + contract to 0.0005 and 0.03. And if we require a high confidence, they + widen to 0.00005 to 0.05. +

+
alpha = 0.1; // 90% confidence.
+t = geometric::find_lower_bound_on_p(k, alpha/2);
+cout << "geometric::find_lower_bound_on_p(" << int(k) << ", " << alpha/2 << ") = "
+  << t << endl; // 0.0005
+t = geometric::find_upper_bound_on_p(k, alpha/2);
+cout << "geometric::find_upper_bound_on_p(" << int(k) << ", " << alpha/2 << ") = "
+  << t << endl; // 0.03
+
+alpha = 0.01; // 99% confidence.
+t = geometric::find_lower_bound_on_p(k, alpha/2);
+cout << "geometric::find_lower_bound_on_p(" << int(k) << ", " << alpha/2 << ") = "
+  << t << endl; // 5e-005
+t = geometric::find_upper_bound_on_p(k, alpha/2);
+cout << "geometric::find_upper_bound_on_p(" << int(k) << ", " << alpha/2 << ") = "
+    << t << endl; // 0.052
+
+

+ In real life, there will usually be more than one event (fault or success), + when the negative binomial, which has the neccessary extra parameter, will + be needed. +

+

+ As noted above, using a catch block is always a good idea, even if you + hope not to use it! +

+
}
+catch(const std::exception& e)
+{ // Since we have set an overflow policy of ignore_error,
+  // an overflow exception should never be thrown.
+   std::cout << "\nMessage from thrown exception was:\n " << e.what() << std::endl;
+
+

+ For example, without a ignore domain error policy, if we asked for +

+
pdf(g, -1)
+

+ for example, we would get an unhelpful abort, but with a catch: +

+
Message from thrown exception was:
+ Error in function boost::math::pdf(const exponential_distribution<double>&, double):
+ Number of failures argument is -1, but must be >= 0 !
+
+

+ See full source C++ of this example at geometric_examples.cpp +

+

+ See + negative_binomial confidence interval example. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/inverse_chi_squared_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/inverse_chi_squared_eg.html new file mode 100644 index 00000000..9fbe8186 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/inverse_chi_squared_eg.html @@ -0,0 +1,360 @@ + + + +Inverse Chi-Squared Distribution Bayes Example + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ The scaled-inversed-chi-squared distribution is the conjugate prior distribution + for the variance (σ2) parameter of a normal distribution with known expectation + (μ). As such it has widespread application in Bayesian statistics: +

+

+ In Bayesian + inference, the strength of belief into certain parameter values + is itself described through a distribution. Parameters hence become themselves + modelled and interpreted as random variables. +

+

+ In this worked example, we perform such a Bayesian analysis by using the + scaled-inverse-chi-squared distribution as prior and posterior distribution + for the variance parameter of a normal distribution. +

+

+ For more general information on Bayesian type of analyses, see: +

+
    +
  • + Andrew Gelman, John B. Carlin, Hal E. Stern, Donald B. Rubin, Bayesian + Data Analysis, 2003, ISBN 978-1439840955. +
  • +
  • + Jim Albert, Bayesian Compution with R, Springer, 2009, ISBN 978-0387922973. +
  • +
+

+ (As the scaled-inversed-chi-squared is another parameterization of the + inverse-gamma distribution, this example could also have used the inverse-gamma + distribution). +

+

+ Consider precision machines which produce balls for a high-quality ball + bearing. Ideally each ball should have a diameter of precisely 3000 μm (3 + mm). Assume that machines generally produce balls of that size on average + (mean), but individual balls can vary slightly in either direction following + (approximately) a normal distribution. Depending on various production + conditions (e.g. raw material used for balls, workplace temperature and + humidity, maintenance frequency and quality) some machines produce balls + tighter distributed around the target of 3000 μm, while others produce balls + with a wider distribution. Therefore the variance parameter of the normal + distribution of the ball sizes varies from machine to machine. An extensive + survey by the precision machinery manufacturer, however, has shown that + most machines operate with a variance between 15 and 50, and near 25 μm2 on + average. +

+

+ Using this information, we want to model the variance of the machines. + The variance is strictly positive, and therefore we look for a statistical + distribution with support in the positive domain of the real numbers. Given + the expectation of the normal distribution of the balls is known (3000 + μm), for reasons of conjugacy, it is customary practice in Bayesian statistics + to model the variance to be scaled-inverse-chi-squared distributed. +

+

+ In a first step, we will try to use the survey information to model the + general knowledge about the variance parameter of machines measured by + the manufacturer. This will provide us with a generic prior distribution + that is applicable if nothing more specific is known about a particular + machine. +

+

+ In a second step, we will then combine the prior-distribution information + in a Bayesian analysis with data on a specific single machine to derive + a posterior distribution for that machine. +

+
+ + Step + one: Using the survey information. +
+

+ Using the survey results, we try to find the parameter set of a scaled-inverse-chi-squared + distribution so that the properties of this distribution match the results. + Using the mathematical properties of the scaled-inverse-chi-squared distribution + as guideline, we see that that both the mean and mode of the scaled-inverse-chi-squared + distribution are approximately given by the scale parameter (s) of the + distribution. As the survey machines operated at a variance of 25 μm2 on + average, we hence set the scale parameter (sprior) of our prior distribution + equal to this value. Using some trial-and-error and calls to the global + quantile function, we also find that a value of 20 for the degrees-of-freedom + (νprior) parameter is adequate so that most of the prior distribution mass + is located between 15 and 50 (see figure below). +

+

+ We first construct our prior distribution using these values, and then + list out a few quantiles: +

+
double priorDF = 20.0;
+double priorScale = 25.0;
+
+inverse_chi_squared prior(priorDF, priorScale);
+// Using an inverse_gamma distribution instead, we could equivalently write
+// inverse_gamma prior(priorDF / 2.0, priorScale * priorDF / 2.0);
+
+cout << "Prior distribution:" << endl << endl;
+cout << "  2.5% quantile: " << quantile(prior, 0.025) << endl;
+cout << "  50% quantile: " << quantile(prior, 0.5) << endl;
+cout << "  97.5% quantile: " << quantile(prior, 0.975) << endl << endl;
+
+

+ This produces this output: +

+
Prior distribution:
+
+2.5% quantile: 14.6
+50% quantile: 25.9
+97.5% quantile: 52.1
+
+

+ Based on this distribution, we can now calculate the probability of having + a machine working with an unusual work precision (variance) at <= 15 + or > 50. For this task, we use calls to the boost::math:: functions cdf + and complement, respectively, + and find a probability of about 0.031 (3.1%) for each case. +

+
cout << "  probability variance <= 15: " << boost::math::cdf(prior, 15.0) << endl;
+cout << "  probability variance <= 25: " << boost::math::cdf(prior, 25.0) << endl;
+cout << "  probability variance > 50: "
+  << boost::math::cdf(boost::math::complement(prior, 50.0))
+<< endl << endl;
+
+

+ This produces this output: +

+
probability variance <= 15: 0.031
+probability variance <= 25: 0.458
+probability variance > 50: 0.0318
+
+

+ Therefore, only 3.1% of all precision machines produce balls with a variance + of 15 or less (particularly precise machines), but also only 3.2% of all + machines produce balls with a variance of as high as 50 or more (particularly + imprecise machines). Moreover, slightly more than one-half (1 - 0.458 = + 54.2%) of the machines work at a variance greater than 25. +

+

+ Notice here the distinction between a Bayesian + analysis and a frequentist + analysis: because we model the variance as random variable itself, we can + calculate and straightforwardly interpret probabilities for given parameter + values directly, while such an approach is not possible (and interpretationally + a strict must-not) in the frequentist world. +

+
+ + Step + 2: Investigate a single machine +
+

+ In the second step, we investigate a single machine, which is suspected + to suffer from a major fault as the produced balls show fairly high size + variability. Based on the prior distribution of generic machinery performance + (derived above) and data on balls produced by the suspect machine, we calculate + the posterior distribution for that machine and use its properties for + guidance regarding continued machine operation or suspension. +

+

+ It can be shown that if the prior distribution was chosen to be scaled-inverse-chi-square + distributed, then the posterior distribution is also scaled-inverse-chi-squared-distributed + (prior and posterior distributions are hence conjugate). For more details + regarding conjugacy and formula to derive the parameters set for the posterior + distribution see Conjugate + prior. +

+

+ Given the prior distribution parameters and sample data (of size n), the + posterior distribution parameters are given by the two expressions: +

+

+    νposterior = νprior + n +

+

+ which gives the posteriorDF below, and +

+

+    sposterior = (νpriorsprior + Σni=1(xi - μ)2) / (νprior + n) +

+

+ which after some rearrangement gives the formula for the posteriorScale + below. +

+

+ Machine-specific data consist of 100 balls which were accurately measured + and show the expected mean of 3000 μm and a sample variance of 55 (calculated + for a sample mean defined to be 3000 exactly). From these data, the prior + parameterization, and noting that the term Σni=1(xi - μ)2 equals the sample + variance multiplied by n - 1, it follows that the posterior distribution + of the variance parameter is scaled-inverse-chi-squared distribution with + degrees-of-freedom (νposterior) = 120 and scale (sposterior) = 49.54. +

+
int ballsSampleSize = 100;
+cout <<"balls sample size: " << ballsSampleSize << endl;
+double ballsSampleVariance = 55.0;
+cout <<"balls sample variance: " << ballsSampleVariance << endl;
+
+double posteriorDF = priorDF + ballsSampleSize;
+cout << "prior degrees-of-freedom: " << priorDF << endl;
+cout << "posterior degrees-of-freedom: " << posteriorDF << endl;
+
+double posteriorScale =
+  (priorDF * priorScale + (ballsSampleVariance * (ballsSampleSize - 1))) / posteriorDF;
+cout << "prior scale: " << priorScale  << endl;
+cout << "posterior scale: " << posteriorScale << endl;
+
+

+ An interesting feature here is that one needs only to know a summary statistics + of the sample to parameterize the posterior distribution: the 100 individual + ball measurements are irrelevant, just knowledge of the sample variance + and number of measurements is sufficient. +

+

+ That produces this output: +

+
balls sample size: 100
+balls sample variance: 55
+prior degrees-of-freedom: 20
+posterior degrees-of-freedom: 120
+prior scale: 25
+posterior scale: 49.5
+
+
+

+ To compare the generic machinery performance with our suspect machine, + we calculate again the same quantiles and probabilities as above, and find + a distribution clearly shifted to greater values (see figure). +

+

+ +

+
inverse_chi_squared posterior(posteriorDF, posteriorScale);
+
+ cout << "Posterior distribution:" << endl << endl;
+ cout << "  2.5% quantile: " << boost::math::quantile(posterior, 0.025) << endl;
+ cout << "  50% quantile: " << boost::math::quantile(posterior, 0.5) << endl;
+ cout << "  97.5% quantile: " << boost::math::quantile(posterior, 0.975) << endl << endl;
+
+ cout << "  probability variance <= 15: " << boost::math::cdf(posterior, 15.0) << endl;
+ cout << "  probability variance <= 25: " << boost::math::cdf(posterior, 25.0) << endl;
+ cout << "  probability variance > 50: "
+   << boost::math::cdf(boost::math::complement(posterior, 50.0)) << endl;
+
+

+ This produces this output: +

+
Posterior distribution:
+
+   2.5% quantile: 39.1
+   50% quantile: 49.8
+   97.5% quantile: 64.9
+
+   probability variance <= 15: 2.97e-031
+   probability variance <= 25: 8.85e-010
+   probability variance > 50: 0.489
+
+

+ Indeed, the probability that the machine works at a low variance (<= + 15) is almost zero, and even the probability of working at average or better + performance is negligibly small (less than one-millionth of a permille). + On the other hand, with an almost near-half probability (49%), the machine + operates in the extreme high variance range of > 50 characteristic for + poorly performing machines. +

+

+ Based on this information the operation of the machine is taken out of + use and serviced. +

+

+ In summary, the Bayesian analysis allowed us to make exact probabilistic + statements about a parameter of interest, and hence provided us results + with straightforward interpretation. +

+

+ A full sample output is: +

+
 Inverse_chi_squared_distribution Bayes example:
+
+   Prior distribution:
+
+    2.5% quantile: 14.6
+    50% quantile: 25.9
+    97.5% quantile: 52.1
+
+    probability variance <= 15: 0.031
+    probability variance <= 25: 0.458
+    probability variance > 50: 0.0318
+
+  balls sample size: 100
+  balls sample variance: 55
+  prior degrees-of-freedom: 20
+  posterior degrees-of-freedom: 120
+  prior scale: 25
+  posterior scale: 49.5
+  Posterior distribution:
+
+    2.5% quantile: 39.1
+    50% quantile: 49.8
+    97.5% quantile: 64.9
+
+    probability variance <= 15: 2.97e-031
+    probability variance <= 25: 8.85e-010
+    probability variance > 50: 0.489
+
+
+

+ (See also the reference documentation for the Inverse + chi squared Distribution.) +

+

+ See the full source C++ of this example at ../../example/inverse_chi_squared_bayes_eg.cpp +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nag_library.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nag_library.html new file mode 100644 index 00000000..45eaf30e --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nag_library.html @@ -0,0 +1,116 @@ + + + +Comparison with C, R, FORTRAN-style Free Functions + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ You are probably familiar with a statistics library that has free functions, + for example the classic NAG + C library and matching NAG + FORTRAN Library, Microsoft + Excel BINOMDIST(number_s,trials,probability_s,cumulative), R, MathCAD + pbinom and many others. +

+

+ If so, you may find 'Distributions as Objects' unfamiliar, if not alien. +

+

+ However, do not panic, both definition + and usage are not really very different. +

+

+ A very simple example of generating the same values as the NAG + C library for the binomial distribution follows. (If you find slightly + different values, the Boost C++ version, using double or better, is very + likely to be the more accurate. Of course, accuracy is not usually a concern + for most applications of this function). +

+

+ The NAG + function specification is +

+
void nag_binomial_dist(Integer n, double p, Integer k,
+double *plek, double *pgtk, double *peqk, NagError *fail)
+
+

+ and is called +

+
g01bjc(n, p, k, &plek, &pgtk, &peqk, NAGERR_DEFAULT);
+
+

+ The equivalent using this Boost C++ library is: +

+
using namespace boost::math;  // Using declaration avoids very long names.
+binomial my_dist(4, 0.5); // c.f. NAG n = 4, p = 0.5
+
+

+ and values can be output thus: +

+
cout
+  << my_dist.trials() << " "             // Echo the NAG input n = 4 trials.
+  << my_dist.success_fraction() << " "   // Echo the NAG input p = 0.5
+  << cdf(my_dist, 2) << "  "             // NAG plek with k = 2
+  << cdf(complement(my_dist, 2)) << "  " // NAG pgtk with k = 2
+  << pdf(my_dist, 2) << endl;            // NAG peqk with k = 2
+
+

+ cdf(dist, k) is + equivalent to NAG library plek, + lower tail probability of <= k +

+

+ cdf(complement(dist, k)) is + equivalent to NAG library pgtk, + upper tail probability of > k +

+

+ pdf(dist, k) is + equivalent to NAG library peqk, + point probability of == k +

+

+ See binomial_example_nag.cpp + for details. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nccs_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nccs_eg.html new file mode 100644 index 00000000..7dccbf73 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nccs_eg.html @@ -0,0 +1,53 @@ + + + +Non Central Chi Squared Example + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ + +

+ (See also the reference documentation for the Noncentral + Chi Squared Distribution.) +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nccs_eg/nccs_power_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nccs_eg/nccs_power_eg.html new file mode 100644 index 00000000..5b9011e7 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/nccs_eg/nccs_power_eg.html @@ -0,0 +1,1287 @@ + + + +Tables of the power function of the chi2 test. + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ This example computes a table of the power of the χ2 +test at the 5% significance + level, for various degrees of freedom and non-centrality parameters. + The table is deliberately the same as Table 6 from "The Non-Central + χ2 and F-Distributions and their applications.", P. B. Patnaik, Biometrika, + Vol. 36, No. 1/2 (June 1949), 202-232. +

+

+ First we need some includes to access the non-central chi squared distribution + (and some basic std output of course). +

+
#include <boost/math/distributions/non_central_chi_squared.hpp>
+using boost::math::chi_squared;
+using boost::math::non_central_chi_squared;
+
+#include <iostream>
+using std::cout; using std::endl;
+using std::setprecision;
+
+int main()
+{
+
+

+ Create a table of the power of the χ2 test at 5% significance level, start + with a table header: +

+
cout << "[table\n[[[nu]]";
+for(int lam = 2; lam <= 20; lam += 2)
+{
+   cout << "[[lambda]=" << lam << "]";
+}
+cout << "]\n";
+
+

+ (Note: the enclosing [] brackets are to format as a table in Boost.Quickbook). +

+

+ Enumerate the rows and columns and print the power of the test for each + table cell: +

+
for(int n = 2; n <= 20; ++n)
+{
+   cout << "[[" << n << "]";
+   for(int lam = 2; lam <= 20; lam += 2)
+   {
+
+

+ Calculate the χ2 statistic for a 5% significance: +

+
double cs = quantile(complement(chi_squared(n), 0.05));
+
+

+ The power of the test is given by the complement of the CDF of the non-central + χ2 distribution: +

+
double beta = cdf(complement(non_central_chi_squared(n, lam), cs));
+
+

+ Then output the cell value: +

+
         cout << "[" << setprecision(3) << beta << "]";
+      }
+      cout << "]" << endl;
+   }
+   cout << "]" << endl;
+}
+
+

+ The output from this program is a table in Boost.Quickbook format as + shown below. +

+

+ We can interpret this as follows - for example if ν=10 and λ=10 then the + power of the test is 0.542 - so we have only a 54% chance of correctly + detecting that our null hypothesis is false, and a 46% chance of incurring + a type II error (failing to reject the null hypothesis when it is in + fact false): +

+
+++++++++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

+ ν +

+
+

+ λ=2 +

+
+

+ λ=4 +

+
+

+ λ=6 +

+
+

+ λ=8 +

+
+

+ λ=10 +

+
+

+ λ=12 +

+
+

+ λ=14 +

+
+

+ λ=16 +

+
+

+ λ=18 +

+
+

+ λ=20 +

+
+

+ 2 +

+
+

+ 0.226 +

+
+

+ 0.415 +

+
+

+ 0.584 +

+
+

+ 0.718 +

+
+

+ 0.815 +

+
+

+ 0.883 +

+
+

+ 0.928 +

+
+

+ 0.957 +

+
+

+ 0.974 +

+
+

+ 0.985 +

+
+

+ 3 +

+
+

+ 0.192 +

+
+

+ 0.359 +

+
+

+ 0.518 +

+
+

+ 0.654 +

+
+

+ 0.761 +

+
+

+ 0.84 +

+
+

+ 0.896 +

+
+

+ 0.934 +

+
+

+ 0.959 +

+
+

+ 0.975 +

+
+

+ 4 +

+
+

+ 0.171 +

+
+

+ 0.32 +

+
+

+ 0.47 +

+
+

+ 0.605 +

+
+

+ 0.716 +

+
+

+ 0.802 +

+
+

+ 0.866 +

+
+

+ 0.912 +

+
+

+ 0.943 +

+
+

+ 0.964 +

+
+

+ 5 +

+
+

+ 0.157 +

+
+

+ 0.292 +

+
+

+ 0.433 +

+
+

+ 0.564 +

+
+

+ 0.677 +

+
+

+ 0.769 +

+
+

+ 0.839 +

+
+

+ 0.89 +

+
+

+ 0.927 +

+
+

+ 0.952 +

+
+

+ 6 +

+
+

+ 0.146 +

+
+

+ 0.27 +

+
+

+ 0.403 +

+
+

+ 0.531 +

+
+

+ 0.644 +

+
+

+ 0.738 +

+
+

+ 0.813 +

+
+

+ 0.869 +

+
+

+ 0.911 +

+
+

+ 0.94 +

+
+

+ 7 +

+
+

+ 0.138 +

+
+

+ 0.252 +

+
+

+ 0.378 +

+
+

+ 0.502 +

+
+

+ 0.614 +

+
+

+ 0.71 +

+
+

+ 0.788 +

+
+

+ 0.849 +

+
+

+ 0.895 +

+
+

+ 0.928 +

+
+

+ 8 +

+
+

+ 0.131 +

+
+

+ 0.238 +

+
+

+ 0.357 +

+
+

+ 0.477 +

+
+

+ 0.588 +

+
+

+ 0.685 +

+
+

+ 0.765 +

+
+

+ 0.829 +

+
+

+ 0.879 +

+
+

+ 0.915 +

+
+

+ 9 +

+
+

+ 0.125 +

+
+

+ 0.225 +

+
+

+ 0.339 +

+
+

+ 0.454 +

+
+

+ 0.564 +

+
+

+ 0.661 +

+
+

+ 0.744 +

+
+

+ 0.811 +

+
+

+ 0.863 +

+
+

+ 0.903 +

+
+

+ 10 +

+
+

+ 0.121 +

+
+

+ 0.215 +

+
+

+ 0.323 +

+
+

+ 0.435 +

+
+

+ 0.542 +

+
+

+ 0.64 +

+
+

+ 0.723 +

+
+

+ 0.793 +

+
+

+ 0.848 +

+
+

+ 0.891 +

+
+

+ 11 +

+
+

+ 0.117 +

+
+

+ 0.206 +

+
+

+ 0.309 +

+
+

+ 0.417 +

+
+

+ 0.523 +

+
+

+ 0.62 +

+
+

+ 0.704 +

+
+

+ 0.775 +

+
+

+ 0.833 +

+
+

+ 0.878 +

+
+

+ 12 +

+
+

+ 0.113 +

+
+

+ 0.198 +

+
+

+ 0.297 +

+
+

+ 0.402 +

+
+

+ 0.505 +

+
+

+ 0.601 +

+
+

+ 0.686 +

+
+

+ 0.759 +

+
+

+ 0.818 +

+
+

+ 0.866 +

+
+

+ 13 +

+
+

+ 0.11 +

+
+

+ 0.191 +

+
+

+ 0.286 +

+
+

+ 0.387 +

+
+

+ 0.488 +

+
+

+ 0.584 +

+
+

+ 0.669 +

+
+

+ 0.743 +

+
+

+ 0.804 +

+
+

+ 0.854 +

+
+

+ 14 +

+
+

+ 0.108 +

+
+

+ 0.185 +

+
+

+ 0.276 +

+
+

+ 0.374 +

+
+

+ 0.473 +

+
+

+ 0.567 +

+
+

+ 0.653 +

+
+

+ 0.728 +

+
+

+ 0.791 +

+
+

+ 0.842 +

+
+

+ 15 +

+
+

+ 0.105 +

+
+

+ 0.179 +

+
+

+ 0.267 +

+
+

+ 0.362 +

+
+

+ 0.459 +

+
+

+ 0.552 +

+
+

+ 0.638 +

+
+

+ 0.713 +

+
+

+ 0.777 +

+
+

+ 0.83 +

+
+

+ 16 +

+
+

+ 0.103 +

+
+

+ 0.174 +

+
+

+ 0.259 +

+
+

+ 0.351 +

+
+

+ 0.446 +

+
+

+ 0.538 +

+
+

+ 0.623 +

+
+

+ 0.699 +

+
+

+ 0.764 +

+
+

+ 0.819 +

+
+

+ 17 +

+
+

+ 0.101 +

+
+

+ 0.169 +

+
+

+ 0.251 +

+
+

+ 0.341 +

+
+

+ 0.434 +

+
+

+ 0.525 +

+
+

+ 0.609 +

+
+

+ 0.686 +

+
+

+ 0.752 +

+
+

+ 0.807 +

+
+

+ 18 +

+
+

+ 0.0992 +

+
+

+ 0.165 +

+
+

+ 0.244 +

+
+

+ 0.332 +

+
+

+ 0.423 +

+
+

+ 0.512 +

+
+

+ 0.596 +

+
+

+ 0.673 +

+
+

+ 0.74 +

+
+

+ 0.796 +

+
+

+ 19 +

+
+

+ 0.0976 +

+
+

+ 0.161 +

+
+

+ 0.238 +

+
+

+ 0.323 +

+
+

+ 0.412 +

+
+

+ 0.5 +

+
+

+ 0.584 +

+
+

+ 0.66 +

+
+

+ 0.728 +

+
+

+ 0.786 +

+
+

+ 20 +

+
+

+ 0.0961 +

+
+

+ 0.158 +

+
+

+ 0.232 +

+
+

+ 0.315 +

+
+

+ 0.402 +

+
+

+ 0.489 +

+
+

+ 0.572 +

+
+

+ 0.648 +

+
+

+ 0.716 +

+
+

+ 0.775 +

+
+

+ See nc_chi_sq_example.cpp + for the full C++ source code. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg.html new file mode 100644 index 00000000..7588620b --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg.html @@ -0,0 +1,62 @@ + + + +Negative Binomial Distribution Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ + +

+ (See also the reference documentation for the Negative + Binomial Distribution.) +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/neg_binom_conf.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/neg_binom_conf.html new file mode 100644 index 00000000..05b11fad --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/neg_binom_conf.html @@ -0,0 +1,221 @@ + + + +Calculating Confidence Limits on the Frequency of Occurrence for the Negative Binomial Distribution + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Imagine you have a process that follows a negative binomial distribution: + for each trial conducted, an event either occurs or does it does not, + referred to as "successes" and "failures". The frequency + with which successes occur is variously referred to as the success fraction, + success ratio, success percentage, occurrence frequency, or probability + of occurrence. +

+

+ If, by experiment, you want to measure the the best estimate of success + fraction is given simply by k / N, + for k successes out of N trials. +

+

+ However our confidence in that estimate will be shaped by how many trials + were conducted, and how many successes were observed. The static member + functions negative_binomial_distribution<>::find_lower_bound_on_p + and negative_binomial_distribution<>::find_upper_bound_on_p + allow you to calculate the confidence intervals for your estimate of + the success fraction. +

+

+ The sample program neg_binom_confidence_limits.cpp + illustrates their use. +

+

+ First we need some includes to access the negative binomial distribution + (and some basic std output of course). +

+
#include <boost/math/distributions/negative_binomial.hpp>
+using boost::math::negative_binomial;
+
+#include <iostream>
+using std::cout; using std::endl;
+#include <iomanip>
+using std::setprecision;
+using std::setw; using std::left; using std::fixed; using std::right;
+
+

+ First define a table of significance levels: these are the probabilities + that the true occurrence frequency lies outside the calculated interval: +

+
double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
+
+

+ Confidence value as % is (1 - alpha) * 100, so alpha 0.05 == 95% confidence + that the true occurrence frequency lies inside + the calculated interval. +

+

+ We need a function to calculate and print confidence limits for an observed + frequency of occurrence that follows a negative binomial distribution. +

+
void confidence_limits_on_frequency(unsigned trials, unsigned successes)
+{
+   // trials = Total number of trials.
+   // successes = Total number of observed successes.
+   // failures = trials - successes.
+   // success_fraction = successes /trials.
+   // Print out general info:
+   cout <<
+      "______________________________________________\n"
+      "2-Sided Confidence Limits For Success Fraction\n"
+      "______________________________________________\n\n";
+   cout << setprecision(7);
+   cout << setw(40) << left << "Number of trials" << " =  " << trials << "\n";
+   cout << setw(40) << left << "Number of successes" << " =  " << successes << "\n";
+   cout << setw(40) << left << "Number of failures" << " =  " << trials - successes << "\n";
+   cout << setw(40) << left << "Observed frequency of occurrence" << " =  " << double(successes) / trials << "\n";
+
+   // Print table header:
+   cout << "\n\n"
+           "___________________________________________\n"
+           "Confidence        Lower          Upper\n"
+           " Value (%)        Limit          Limit\n"
+           "___________________________________________\n";
+
+

+ And now for the important part - the bounds themselves. For each value + of alpha, we call find_lower_bound_on_p + and find_upper_bound_on_p + to obtain lower and upper bounds respectively. Note that since we are + calculating a two-sided interval, we must divide the value of alpha in + two. Had we been calculating a single-sided interval, for example: "Calculate + a lower bound so that we are P% sure that the true occurrence frequency + is greater than some value" then we would not + have divided by two. +

+
   // Now print out the upper and lower limits for the alpha table values.
+   for(unsigned i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)
+   {
+      // Confidence value:
+      cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]);
+      // Calculate bounds:
+      double lower = negative_binomial::find_lower_bound_on_p(trials, successes, alpha[i]/2);
+      double upper = negative_binomial::find_upper_bound_on_p(trials, successes, alpha[i]/2);
+      // Print limits:
+      cout << fixed << setprecision(5) << setw(15) << right << lower;
+      cout << fixed << setprecision(5) << setw(15) << right << upper << endl;
+   }
+   cout << endl;
+} // void confidence_limits_on_frequency(unsigned trials, unsigned successes)
+
+

+ And then call confidence_limits_on_frequency with increasing numbers + of trials, but always the same success fraction 0.1, or 1 in 10. +

+
int main()
+{
+  confidence_limits_on_frequency(20, 2); // 20 trials, 2 successes, 2 in 20, = 1 in 10 = 0.1 success fraction.
+  confidence_limits_on_frequency(200, 20); // More trials, but same 0.1 success fraction.
+  confidence_limits_on_frequency(2000, 200); // Many more trials, but same 0.1 success fraction.
+
+  return 0;
+} // int main()
+
+

+ Let's see some sample output for a 1 in 10 success ratio, first for a + mere 20 trials: +

+
______________________________________________
+2-Sided Confidence Limits For Success Fraction
+______________________________________________
+Number of trials                         =  20
+Number of successes                      =  2
+Number of failures                       =  18
+Observed frequency of occurrence         =  0.1
+___________________________________________
+Confidence        Lower          Upper
+ Value (%)        Limit          Limit
+___________________________________________
+    50.000        0.04812        0.13554
+    75.000        0.03078        0.17727
+    90.000        0.01807        0.22637
+    95.000        0.01235        0.26028
+    99.000        0.00530        0.33111
+    99.900        0.00164        0.41802
+    99.990        0.00051        0.49202
+    99.999        0.00016        0.55574
+
+

+ As you can see, even at the 95% confidence level the bounds (0.012 to + 0.26) are really very wide, and very asymmetric about the observed value + 0.1. +

+

+ Compare that with the program output for a mass 2000 trials: +

+
______________________________________________
+2-Sided Confidence Limits For Success Fraction
+______________________________________________
+Number of trials                         =  2000
+Number of successes                      =  200
+Number of failures                       =  1800
+Observed frequency of occurrence         =  0.1
+___________________________________________
+Confidence        Lower          Upper
+ Value (%)        Limit          Limit
+___________________________________________
+    50.000        0.09536        0.10445
+    75.000        0.09228        0.10776
+    90.000        0.08916        0.11125
+    95.000        0.08720        0.11352
+    99.000        0.08344        0.11802
+    99.900        0.07921        0.12336
+    99.990        0.07577        0.12795
+    99.999        0.07282        0.13206
+
+

+ Now even when the confidence level is very high, the limits (at 99.999%, + 0.07 to 0.13) are really quite close and nearly symmetric to the observed + value of 0.1. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/neg_binom_size_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/neg_binom_size_eg.html new file mode 100644 index 00000000..b25a385e --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/neg_binom_size_eg.html @@ -0,0 +1,207 @@ + + + +Estimating Sample Sizes for the Negative Binomial. + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Imagine you have an event (let's call it a "failure" - though + we could equally well call it a success if we felt it was a 'good' event) + that you know will occur in 1 in N trials. You may want to know how many + trials you need to conduct to be P% sure of observing at least k such + failures. If the failure events follow a negative binomial distribution + (each trial either succeeds or fails) then the static member function + negative_binomial_distibution<>::find_minimum_number_of_trials + can be used to estimate the minimum number of trials required to be P% + sure of observing the desired number of failures. +

+

+ The example program neg_binomial_sample_sizes.cpp + demonstrates its usage. +

+

+ It centres around a routine that prints out a table of minimum sample + sizes (number of trials) for various probability thresholds: +

+
void find_number_of_trials(double failures, double p);
+
+

+ First define a table of significance levels: these are the maximum acceptable + probability that failure or fewer events will be + observed. +

+
double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
+
+

+ Confidence value as % is (1 - alpha) * 100, so alpha 0.05 == 95% confidence + that the desired number of failures will be observed. The values range + from a very low 0.5 or 50% confidence up to an extremely high confidence + of 99.999. +

+

+ Much of the rest of the program is pretty-printing, the important part + is in the calculation of minimum number of trials required for each value + of alpha using: +

+
(int)ceil(negative_binomial::find_minimum_number_of_trials(failures, p, alpha[i]);
+
+

+ find_minimum_number_of_trials returns a double, so ceil + rounds this up to ensure we have an integral minimum number of trials. +

+
void find_number_of_trials(double failures, double p)
+{
+   // trials = number of trials
+   // failures = number of failures before achieving required success(es).
+   // p        = success fraction (0 <= p <= 1.).
+   //
+   // Calculate how many trials we need to ensure the
+   // required number of failures DOES exceed "failures".
+
+  cout << "\n""Target number of failures = " << (int)failures;
+  cout << ",   Success fraction = " << fixed << setprecision(1) << 100 * p << "%" << endl;
+   // Print table header:
+   cout << "____________________________\n"
+           "Confidence        Min Number\n"
+           " Value (%)        Of Trials \n"
+           "____________________________\n";
+   // Now print out the data for the alpha table values.
+  for(unsigned i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)
+   { // Confidence values %:
+      cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]) << "      "
+      // find_minimum_number_of_trials
+      << setw(6) << right
+      << (int)ceil(negative_binomial::find_minimum_number_of_trials(failures, p, alpha[i]))
+      << endl;
+   }
+   cout << endl;
+} // void find_number_of_trials(double failures, double p)
+
+

+ finally we can produce some tables of minimum trials for the chosen confidence + levels: +

+
int main()
+{
+    find_number_of_trials(5, 0.5);
+    find_number_of_trials(50, 0.5);
+    find_number_of_trials(500, 0.5);
+    find_number_of_trials(50, 0.1);
+    find_number_of_trials(500, 0.1);
+    find_number_of_trials(5, 0.9);
+
+    return 0;
+} // int main()
+
+
+ + + + + +
[Note]Note
+

+ Since we're calculating the minimum number of + trials required, we'll err on the safe side and take the ceiling of + the result. Had we been calculating the maximum + number of trials permitted to observe less than a certain number of + failures then we would have taken the floor instead. + We would also have called find_minimum_number_of_trials + like this: +

+
floor(negative_binomial::find_minimum_number_of_trials(failures, p, alpha[i]))
+
+

+ which would give us the largest number of trials we could conduct and + still be P% sure of observing failures or less + failure events, when the probability of success is p. +

+
+

+ We'll finish off by looking at some sample output, firstly suppose we + wish to observe at least 5 "failures" with a 50/50 (0.5) chance + of success or failure: +

+
Target number of failures = 5,   Success fraction = 50%
+
+____________________________
+Confidence        Min Number
+ Value (%)        Of Trials
+____________________________
+    50.000          11
+    75.000          14
+    90.000          17
+    95.000          18
+    99.000          22
+    99.900          27
+    99.990          31
+    99.999          36
+
+
+

+ So 18 trials or more would yield a 95% chance that at least our 5 required + failures would be observed. +

+

+ Compare that to what happens if the success ratio is 90%: +

+
Target number of failures = 5.000,   Success fraction = 90.000%
+
+____________________________
+Confidence        Min Number
+ Value (%)        Of Trials
+____________________________
+    50.000          57
+    75.000          73
+    90.000          91
+    95.000         103
+    99.000         127
+    99.900         159
+    99.990         189
+    99.999         217
+
+

+ So now 103 trials are required to observe at least 5 failures with 95% + certainty. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/negative_binomial_example1.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/negative_binomial_example1.html new file mode 100644 index 00000000..944ccbd0 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/negative_binomial_example1.html @@ -0,0 +1,507 @@ + + + +Negative Binomial Sales Quota Example. + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ This example program negative_binomial_example1.cpp + (full source code) demonstrates a simple use to find the probability + of meeting a sales quota. +

+

+ Based on a + problem by Dr. Diane Evans, Professor of Mathematics at Rose-Hulman Institute + of Technology. +

+

+ Pat is required to sell candy bars to raise money for the 6th grade field + trip. There are thirty houses in the neighborhood, and Pat is not supposed + to return home until five candy bars have been sold. So the child goes + door to door, selling candy bars. At each house, there is a 0.4 probability + (40%) of selling one candy bar and a 0.6 probability (60%) of selling + nothing. +

+

+ What is the probability mass (density) function (pdf) for selling the + last (fifth) candy bar at the nth house? +

+

+ The Negative Binomial(r, p) distribution describes the probability of + k failures and r successes in k+r Bernoulli(p) trials with success on + the last trial. (A Bernoulli + trial is one with only two possible outcomes, success of failure, + and p is the probability of success). See also Bernoulli + distribution and Bernoulli + applications. +

+

+ In this example, we will deliberately produce a variety of calculations + and outputs to demonstrate the ways that the negative binomial distribution + can be implemented with this library: it is also deliberately over-commented. +

+

+ First we need to #define macros to control the error and discrete handling + policies. For this simple example, we want to avoid throwing an exception + (the default policy) and just return infinity. We want to treat the distribution + as if it was continuous, so we choose a discrete_quantile policy of real, + rather than the default policy integer_round_outwards. +

+
#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error
+#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real
+
+

+ After that we need some includes to provide easy access to the negative + binomial distribution, +

+
+ + + + + +
[Caution]Caution

+ It is vital to #include distributions etc after + the above #defines +

+

+ and we need some std library iostream, of course. +

+
#include <boost/math/distributions/negative_binomial.hpp>
+  // for negative_binomial_distribution
+  using boost::math::negative_binomial; // typedef provides default type is double.
+  using  ::boost::math::pdf; // Probability mass function.
+  using  ::boost::math::cdf; // Cumulative density function.
+  using  ::boost::math::quantile;
+
+#include <iostream>
+  using std::cout; using std::endl;
+  using std::noshowpoint; using std::fixed; using std::right; using std::left;
+#include <iomanip>
+  using std::setprecision; using std::setw;
+
+#include <limits>
+  using std::numeric_limits;
+
+

+ It is always sensible to use try and catch blocks because defaults policies + are to throw an exception if anything goes wrong. +

+

+ A simple catch block (see below) will ensure that you get a helpful error + message instead of an abrupt program abort. +

+
try
+{
+
+

+ Selling five candy bars means getting five successes, so successes r + = 5. The total number of trials (n, in this case, houses visited) this + takes is therefore = sucesses + failures or k + r = k + 5. +

+
double sales_quota = 5; // Pat's sales quota - successes (r).
+
+

+ At each house, there is a 0.4 probability (40%) of selling one candy + bar and a 0.6 probability (60%) of selling nothing. +

+
double success_fraction = 0.4; // success_fraction (p) - so failure_fraction is 0.6.
+
+

+ The Negative Binomial(r, p) distribution describes the probability of + k failures and r successes in k+r Bernoulli(p) trials with success on + the last trial. (A Bernoulli + trial is one with only two possible outcomes, success of failure, + and p is the probability of success). +

+

+ We therefore start by constructing a negative binomial distribution with + parameters sales_quota (required successes) and probability of success. +

+
negative_binomial nb(sales_quota, success_fraction); // type double by default.
+
+

+ To confirm, display the success_fraction & successes parameters of + the distribution. +

+
cout << "Pat has a sales per house success rate of " << success_fraction
+  << ".\nTherefore he would, on average, sell " << nb.success_fraction() * 100
+  << " bars after trying 100 houses." << endl;
+
+int all_houses = 30; // The number of houses on the estate.
+
+cout << "With a success rate of " << nb.success_fraction()
+  << ", he might expect, on average,\n"
+    "to need to visit about " << success_fraction * all_houses
+    << " houses in order to sell all " << nb.successes() << " bars. " << endl;
+
+
Pat has a sales per house success rate of 0.4.
+Therefore he would, on average, sell 40 bars after trying 100 houses.
+With a success rate of 0.4, he might expect, on average,
+to need to visit about 12 houses in order to sell all 5 bars.
+
+

+ The random variable of interest is the number of houses that must be + visited to sell five candy bars, so we substitute k = n - 5 into a negative_binomial(5, + 0.4) and obtain the Probability + Density Function of the distribution of houses visited. Obviously, + the best possible case is that Pat makes sales on all the first five + houses. +

+

+ We calculate this using the pdf function: +

+
cout << "Probability that Pat finishes on the " << sales_quota << "th house is "
+  << pdf(nb, 5 - sales_quota) << endl; // == pdf(nb, 0)
+
+

+ Of course, he could not finish on fewer than 5 houses because he must + sell 5 candy bars. So the 5th house is the first that he could possibly + finish on. +

+

+ To finish on or before the 8th house, Pat must finish at the 5th, 6th, + 7th or 8th house. The probability that he will finish on exactly + ( == ) on any house is the Probability Density Function (pdf). +

+
cout << "Probability that Pat finishes on the 6th house is "
+  << pdf(nb, 6 - sales_quota) << endl;
+cout << "Probability that Pat finishes on the 7th house is "
+  << pdf(nb, 7 - sales_quota) << endl;
+cout << "Probability that Pat finishes on the 8th house is "
+  << pdf(nb, 8 - sales_quota) << endl;
+
+
Probability that Pat finishes on the 6th house is 0.03072
+Probability that Pat finishes on the 7th house is 0.055296
+Probability that Pat finishes on the 8th house is 0.077414
+
+

+ The sum of the probabilities for these houses is the Cumulative Distribution + Function (cdf). We can calculate it by adding the individual probabilities. +

+
cout << "Probability that Pat finishes on or before the 8th house is sum "
+  "\n" << "pdf(sales_quota) + pdf(6) + pdf(7) + pdf(8) = "
+  // Sum each of the mass/density probabilities for houses sales_quota = 5, 6, 7, & 8.
+  << pdf(nb, 5 - sales_quota) // 0 failures.
+    + pdf(nb, 6 - sales_quota) // 1 failure.
+    + pdf(nb, 7 - sales_quota) // 2 failures.
+    + pdf(nb, 8 - sales_quota) // 3 failures.
+  << endl;
+
+
pdf(sales_quota) + pdf(6) + pdf(7) + pdf(8) = 0.17367
+
+

+ Or, usually better, by using the negative binomial cumulative + distribution function. +

+
cout << "\nProbability of selling his quota of " << sales_quota
+  << " bars\non or before the " << 8 << "th house is "
+  << cdf(nb, 8 - sales_quota) << endl;
+
+
Probability of selling his quota of 5 bars on or before the 8th house is 0.17367
+
+
cout << "\nProbability that Pat finishes exactly on the 10th house is "
+  << pdf(nb, 10 - sales_quota) << endl;
+cout << "\nProbability of selling his quota of " << sales_quota
+  << " bars\non or before the " << 10 << "th house is "
+  << cdf(nb, 10 - sales_quota) << endl;
+
+
Probability that Pat finishes exactly on the 10th house is 0.10033
+Probability of selling his quota of 5 bars on or before the 10th house is 0.3669
+
+
cout << "Probability that Pat finishes exactly on the 11th house is "
+  << pdf(nb, 11 - sales_quota) << endl;
+cout << "\nProbability of selling his quota of " << sales_quota
+  << " bars\non or before the " << 11 << "th house is "
+  << cdf(nb, 11 - sales_quota) << endl;
+
+
Probability that Pat finishes on the 11th house is 0.10033
+Probability of selling his quota of 5 candy bars
+on or before the 11th house is 0.46723
+
+
cout << "Probability that Pat finishes exactly on the 12th house is "
+  << pdf(nb, 12 - sales_quota) << endl;
+
+cout << "\nProbability of selling his quota of " << sales_quota
+  << " bars\non or before the " << 12 << "th house is "
+  << cdf(nb, 12 - sales_quota) << endl;
+
+
Probability that Pat finishes on the 12th house is 0.094596
+Probability of selling his quota of 5 candy bars
+on or before the 12th house is 0.56182
+
+

+ Finally consider the risk of Pat not selling his quota of 5 bars even + after visiting all the houses. Calculate the probability that he will + sell on or before the last house: Calculate the probability that he would + sell all his quota on the very last house. +

+
cout << "Probability that Pat finishes on the " << all_houses
+  << " house is " << pdf(nb, all_houses - sales_quota) << endl;
+
+

+ Probability of selling his quota of 5 bars on the 30th house is +

+
Probability that Pat finishes on the 30 house is 0.00069145
+
+

+ when he'd be very unlucky indeed! +

+

+ What is the probability that Pat exhausts all 30 houses in the neighborhood, + and still doesn't sell the required + 5 candy bars? +

+
cout << "\nProbability of selling his quota of " << sales_quota
+  << " bars\non or before the " << all_houses << "th house is "
+  << cdf(nb, all_houses - sales_quota) << endl;
+
+
Probability of selling his quota of 5 bars
+on or before the 30th house is 0.99849
+
+

+ /*So the + risk of + failing even + after visiting + all the + houses is + 1 - this probability, 1 + - cdf(nb, all_houses + - sales_quota + But using + this expression + may cause + serious inaccuracy, so it would + be much + better to + use the + complement of + the cdf: So the risk + of failing + even at, or after, the 31th (non-existent) + houses is + 1 - this probability, 1 + - cdf(nb, all_houses + - sales_quota)` But using this expression may cause + serious inaccuracy. So it would be much better to use the __complement + of the cdf (see why complements?). +

+
cout << "\nProbability of failing to sell his quota of " << sales_quota
+  << " bars\neven after visiting all " << all_houses << " houses is "
+  << cdf(complement(nb, all_houses - sales_quota)) << endl;
+
+
Probability of failing to sell his quota of 5 bars
+even after visiting all 30 houses is 0.0015101
+
+

+ We can also use the quantile (percentile), the inverse of the cdf, to + predict which house Pat will finish on. So for the 8th house: +

+
double p = cdf(nb, (8 - sales_quota));
+cout << "Probability of meeting sales quota on or before 8th house is "<< p << endl;
+
+
Probability of meeting sales quota on or before 8th house is 0.174
+
+
cout << "If the confidence of meeting sales quota is " << p
+    << ", then the finishing house is " << quantile(nb, p) + sales_quota << endl;
+
+cout<< " quantile(nb, p) = " << quantile(nb, p) << endl;
+
+
If the confidence of meeting sales quota is 0.17367, then the finishing house is 8
+
+

+ Demanding absolute certainty that all 5 will be sold, implies an infinite + number of trials. (Of course, there are only 30 houses on the estate, + so he can't ever be certain of selling + his quota). +

+
cout << "If the confidence of meeting sales quota is " << 1.
+    << ", then the finishing house is " << quantile(nb, 1) + sales_quota << endl;
+//  1.#INF == infinity.
+
+
If the confidence of meeting sales quota is 1, then the finishing house is 1.#INF
+
+

+ And similarly for a few other probabilities: +

+
cout << "If the confidence of meeting sales quota is " << 0.
+    << ", then the finishing house is " << quantile(nb, 0.) + sales_quota << endl;
+
+cout << "If the confidence of meeting sales quota is " << 0.5
+    << ", then the finishing house is " << quantile(nb, 0.5) + sales_quota << endl;
+
+cout << "If the confidence of meeting sales quota is " << 1 - 0.00151 // 30 th
+    << ", then the finishing house is " << quantile(nb, 1 - 0.00151) + sales_quota << endl;
+
+
If the confidence of meeting sales quota is 0, then the finishing house is 5
+If the confidence of meeting sales quota is 0.5, then the finishing house is 11.337
+If the confidence of meeting sales quota is 0.99849, then the finishing house is 30
+
+

+ Notice that because we chose a discrete quantile policy of real, the + result can be an 'unreal' fractional house. +

+

+ If the opposite is true, we don't want to assume any confidence, then + this is tantamount to assuming that all the first sales_quota trials + will be successful sales. +

+
cout << "If confidence of meeting quota is zero\n(we assume all houses are successful sales)"
+  ", then finishing house is " << sales_quota << endl;
+
+
If confidence of meeting quota is zero (we assume all houses are successful sales), then finishing house is 5
+If confidence of meeting quota is 0, then finishing house is 5
+
+

+ We can list quantiles for a few probabilities: +

+
 double ps[] = {0., 0.001, 0.01, 0.05, 0.1, 0.5, 0.9, 0.95, 0.99, 0.999, 1.};
+ // Confidence as fraction = 1-alpha, as percent =  100 * (1-alpha[i]) %
+ cout.precision(3);
+ for (int i = 0; i < sizeof(ps)/sizeof(ps[0]); i++)
+ {
+   cout << "If confidence of meeting quota is " << ps[i]
+     << ", then finishing house is " << quantile(nb, ps[i]) + sales_quota
+     << endl;
+}
+
+
If confidence of meeting quota is 0, then finishing house is 5
+If confidence of meeting quota is 0.001, then finishing house is 5
+If confidence of meeting quota is 0.01, then finishing house is 5
+If confidence of meeting quota is 0.05, then finishing house is 6.2
+If confidence of meeting quota is 0.1, then finishing house is 7.06
+If confidence of meeting quota is 0.5, then finishing house is 11.3
+If confidence of meeting quota is 0.9, then finishing house is 17.8
+If confidence of meeting quota is 0.95, then finishing house is 20.1
+If confidence of meeting quota is 0.99, then finishing house is 24.8
+If confidence of meeting quota is 0.999, then finishing house is 31.1
+If confidence of meeting quota is 1, then finishing house is 1.#INF
+
+

+ We could have applied a ceil function to obtain a 'worst case' integer + value for house. +

+
ceil(quantile(nb, ps[i]))
+

+ Or, if we had used the default discrete quantile policy, integer_outside, + by omitting +

+
#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real
+

+ we would have achieved the same effect. +

+

+ The real result gives some suggestion which house is most likely. For + example, compare the real and integer_outside for 95% confidence. +

+
If confidence of meeting quota is 0.95, then finishing house is 20.1
+If confidence of meeting quota is 0.95, then finishing house is 21
+
+

+ The real value 20.1 is much closer to 20 than 21, so integer_outside + is pessimistic. We could also use integer_round_nearest policy to suggest + that 20 is more likely. +

+

+ Finally, we can tabulate the probability for the last sale being exactly + on each house. +

+
cout << "\nHouse for " << sales_quota << "th (last) sale.  Probability (%)" << endl;
+cout.precision(5);
+for (int i = (int)sales_quota; i < all_houses+1; i++)
+{
+  cout << left << setw(3) << i << "                             " << setw(8) << cdf(nb, i - sales_quota)  << endl;
+}
+cout << endl;
+
+
House for 5 th (last) sale.  Probability (%)
+5                               0.01024
+6                               0.04096
+7                               0.096256
+8                               0.17367
+9                               0.26657
+10                              0.3669
+11                              0.46723
+12                              0.56182
+13                              0.64696
+14                              0.72074
+15                              0.78272
+16                              0.83343
+17                              0.874
+18                              0.90583
+19                              0.93039
+20                              0.94905
+21                              0.96304
+22                              0.97342
+23                              0.98103
+24                              0.98655
+25                              0.99053
+26                              0.99337
+27                              0.99539
+28                              0.99681
+29                              0.9978
+30                              0.99849
+
+

+ As noted above, using a catch block is always a good idea, even if you + do not expect to use it. +

+
}
+catch(const std::exception& e)
+{ // Since we have set an overflow policy of ignore_error,
+  // an overflow exception should never be thrown.
+   std::cout << "\nMessage from thrown exception was:\n " << e.what() << std::endl;
+
+

+ For example, without a ignore domain error policy, if we asked for +

+
pdf(nb, -1)
+

+ for example, we would get: +

+
Message from thrown exception was:
+ Error in function boost::math::pdf(const negative_binomial_distribution<double>&, double):
+ Number of failures argument is -1, but must be >= 0 !
+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/negative_binomial_example2.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/negative_binomial_example2.html new file mode 100644 index 00000000..d9ccf4d7 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/neg_binom_eg/negative_binomial_example2.html @@ -0,0 +1,136 @@ + + + +Negative Binomial Table Printing Example. + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Example program showing output of a table of values of cdf and pdf for + various k failures. +

+
// Print a table of values that can be used to plot
+// using Excel, or some other superior graphical display tool.
+
+cout.precision(17); // Use max_digits10 precision, the maximum available for a reference table.
+cout << showpoint << endl; // include trailing zeros.
+// This is a maximum possible precision for the type (here double) to suit a reference table.
+int maxk = static_cast<int>(2. * mynbdist.successes() /  mynbdist.success_fraction());
+// This maxk shows most of the range of interest, probability about 0.0001 to 0.999.
+cout << "\n"" k            pdf                      cdf""\n" << endl;
+for (int k = 0; k < maxk; k++)
+{
+  cout << right << setprecision(17) << showpoint
+    << right << setw(3) << k  << ", "
+    << left << setw(25) << pdf(mynbdist, static_cast<double>(k))
+    << left << setw(25) << cdf(mynbdist, static_cast<double>(k))
+    << endl;
+}
+cout << endl;
+
+
k            pdf                      cdf
+ 0, 1.5258789062500000e-005  1.5258789062500003e-005
+ 1, 9.1552734375000000e-005  0.00010681152343750000
+ 2, 0.00030899047851562522   0.00041580200195312500
+ 3, 0.00077247619628906272   0.0011882781982421875
+ 4, 0.0015932321548461918    0.0027815103530883789
+ 5, 0.0028678178787231476    0.0056493282318115234
+ 6, 0.0046602040529251142    0.010309532284736633
+ 7, 0.0069903060793876605    0.017299838364124298
+ 8, 0.0098301179241389001    0.027129956288263202
+ 9, 0.013106823898851871     0.040236780187115073
+10, 0.016711200471036140     0.056947980658151209
+11, 0.020509200578089786     0.077457181236241013
+12, 0.024354675686481652     0.10181185692272265
+13, 0.028101548869017230     0.12991340579173993
+14, 0.031614242477644432     0.16152764826938440
+15, 0.034775666725408917     0.19630331499479325
+16, 0.037492515688331451     0.23379583068312471
+17, 0.039697957787645101     0.27349378847076977
+18, 0.041352039362130305     0.31484582783290005
+19, 0.042440250924291580     0.35728607875719176
+20, 0.042970754060845245     0.40025683281803687
+21, 0.042970754060845225     0.44322758687888220
+22, 0.042482450037426581     0.48571003691630876
+23, 0.041558918514873783     0.52726895543118257
+24, 0.040260202311284021     0.56752915774246648
+25, 0.038649794218832620     0.60617895196129912
+26, 0.036791631035234917     0.64297058299653398
+27, 0.034747651533277427     0.67771823452981139
+28, 0.032575923312447595     0.71029415784225891
+29, 0.030329307911589130     0.74062346575384819
+30, 0.028054609818219924     0.76867807557206813
+31, 0.025792141284492545     0.79447021685656061
+32, 0.023575629142856460     0.81804584599941710
+33, 0.021432390129869489     0.83947823612928651
+34, 0.019383705779220189     0.85886194190850684
+35, 0.017445335201298231     0.87630727710980494
+36, 0.015628112784496322     0.89193538989430121
+37, 0.013938587078064250     0.90587397697236549
+38, 0.012379666154859701     0.91825364312722524
+39, 0.010951243136991251     0.92920488626421649
+40, 0.0096507830144735539    0.93885566927869002
+41, 0.0084738582566109364    0.94732952753530097
+42, 0.0074146259745345548    0.95474415350983555
+43, 0.0064662435824429246    0.96121039709227851
+44, 0.0056212231142827853    0.96683162020656122
+45, 0.0048717266990450708    0.97170334690560634
+46, 0.0042098073105878630    0.97591315421619418
+47, 0.0036275999165703964    0.97954075413276465
+48, 0.0031174686783026818    0.98265822281106729
+49, 0.0026721160099737302    0.98533033882104104
+50, 0.0022846591885275322    0.98761499800956853
+51, 0.0019486798960970148    0.98956367790566557
+52, 0.0016582516423517923    0.99122192954801736
+53, 0.0014079495076571762    0.99262987905567457
+54, 0.0011928461106539983    0.99382272516632852
+55, 0.0010084971662802015    0.99483122233260868
+56, 0.00085091948404891532   0.99568214181665760
+57, 0.00071656377604119542   0.99639870559269883
+58, 0.00060228420831048650   0.99700098980100937
+59, 0.00050530624256557675   0.99750629604357488
+60, 0.00042319397814867202   0.99792949002172360
+61, 0.00035381791615708398   0.99828330793788067
+62, 0.00029532382517950324   0.99857863176306016
+63, 0.00024610318764958566   0.99882473495070978
+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/normal_example.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/normal_example.html new file mode 100644 index 00000000..c49fe556 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/normal_example.html @@ -0,0 +1,53 @@ + + + +Normal Distribution Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ + +

+ (See also the reference documentation for the Normal + Distribution.) +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/normal_example/normal_misc.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/normal_example/normal_misc.html new file mode 100644 index 00000000..49863042 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/normal_example/normal_misc.html @@ -0,0 +1,518 @@ + + + +Some Miscellaneous Examples of the Normal (Gaussian) Distribution + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ The sample program normal_misc_examples.cpp + illustrates their use. +

+
+ + Traditional + Tables +
+

+ First we need some includes to access the normal distribution (and some + std output of course). +

+
#include <boost/math/distributions/normal.hpp> // for normal_distribution
+  using boost::math::normal; // typedef provides default type is double.
+
+#include <iostream>
+  using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;
+#include <iomanip>
+  using std::setw; using std::setprecision;
+#include <limits>
+  using std::numeric_limits;
+
+int main()
+{
+  cout << "Example: Normal distribution, Miscellaneous Applications.";
+
+  try
+  {
+    { // Traditional tables and values.
+
+

+ Let's start by printing some traditional tables. +

+
double step = 1.; // in z
+double range = 4; // min and max z = -range to +range.
+int precision = 17; // traditional tables are only computed to much lower precision.
+// but std::numeric_limits<double>::max_digits10; on new Standard Libraries gives
+// 17, the maximum number of digits that can possibly be significant.
+// std::numeric_limits<double>::digits10; == 15 is number of guaranteed digits,
+// the other two digits being 'noisy'.
+
+// Construct a standard normal distribution s
+  normal s; // (default mean = zero, and standard deviation = unity)
+  cout << "Standard normal distribution, mean = "<< s.mean()
+    << ", standard deviation = " << s.standard_deviation() << endl;
+
+

+ First the probability distribution function (pdf). +

+
cout << "Probability distribution function values" << endl;
+cout << "  z " "      pdf " << endl;
+cout.precision(5);
+for (double z = -range; z < range + step; z += step)
+{
+  cout << left << setprecision(3) << setw(6) << z << " "
+    << setprecision(precision) << setw(12) << pdf(s, z) << endl;
+}
+cout.precision(6); // default
+
+

+ And the area under the normal curve from -∞ up to z, the cumulative distribution + function (cdf). +

+
// For a standard normal distribution
+cout << "Standard normal mean = "<< s.mean()
+  << ", standard deviation = " << s.standard_deviation() << endl;
+cout << "Integral (area under the curve) from - infinity up to z " << endl;
+cout << "  z " "      cdf " << endl;
+for (double z = -range; z < range + step; z += step)
+{
+  cout << left << setprecision(3) << setw(6) << z << " "
+    << setprecision(precision) << setw(12) << cdf(s, z) << endl;
+}
+cout.precision(6); // default
+
+

+ And all this you can do with a nanoscopic amount of work compared to + the team of human computers toiling + with Milton Abramovitz and Irene Stegen at the US National Bureau of + Standards (now NIST). Starting + in 1938, their "Handbook of Mathematical Functions with Formulas, + Graphs and Mathematical Tables", was eventually published in 1964, + and has been reprinted numerous times since. (A major replacement is + planned at Digital Library of Mathematical + Functions). +

+

+ Pretty-printing a traditional 2-dimensional table is left as an exercise + for the student, but why bother now that the Math Toolkit lets you write +

+
double z = 2.;
+cout << "Area for z = " << z << " is " << cdf(s, z) << endl; // to get the area for z.
+
+

+ Correspondingly, we can obtain the traditional 'critical' values for + significance levels. For the 95% confidence level, the significance level + usually called alpha, is 0.05 = 1 - 0.95 (for a one-sided test), so we + can write +

+
  cout << "95% of area has a z below " << quantile(s, 0.95) << endl;
+// 95% of area has a z below 1.64485
+
+

+ and a two-sided test (a comparison between two levels, rather than a + one-sided test) +

+
  cout << "95% of area has a z between " << quantile(s, 0.975)
+    << " and " << -quantile(s, 0.975) << endl;
+// 95% of area has a z between 1.95996 and -1.95996
+
+

+ First, define a table of significance levels: these are the probabilities + that the true occurrence frequency lies outside the calculated interval. +

+

+ It is convenient to have an alpha level for the probability that z lies + outside just one standard deviation. This will not be some nice neat + number like 0.05, but we can easily calculate it, +

+
double alpha1 = cdf(s, -1) * 2; // 0.3173105078629142
+cout << setprecision(17) << "Significance level for z == 1 is " << alpha1 << endl;
+
+

+ and place in our array of favorite alpha values. +

+
double alpha[] = {0.3173105078629142, // z for 1 standard deviation.
+  0.20, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
+
+

+ Confidence value as % is (1 - alpha) * 100 (so alpha 0.05 == 95% confidence) + that the true occurrence frequency lies inside + the calculated interval. +

+
cout << "level of significance (alpha)" << setprecision(4) << endl;
+cout << "2-sided       1 -sided          z(alpha) " << endl;
+for (int i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)
+{
+  cout << setw(15) << alpha[i] << setw(15) << alpha[i] /2 << setw(10) << quantile(complement(s,  alpha[i]/2)) << endl;
+  // Use quantile(complement(s, alpha[i]/2)) to avoid potential loss of accuracy from quantile(s,  1 - alpha[i]/2)
+}
+cout << endl;
+
+

+ Notice the distinction between one-sided (also called one-tailed) where + we are using a > or < test (and + not both) and considering the area of the tail (integral) from z up to + +∞, and a two-sided test where we are using two > and + < tests, and thus considering two tails, from -∞ up to z low and z high + up to +∞. +

+

+ So the 2-sided values alpha[i] are calculated using alpha[i]/2. +

+

+ If we consider a simple example of alpha = 0.05, then for a two-sided + test, the lower tail area from -∞ up to -1.96 is 0.025 (alpha/2) and the + upper tail area from +z up to +1.96 is also 0.025 (alpha/2), and the + area between -1.96 up to 12.96 is alpha = 0.95. and the sum of the two + tails is 0.025 + 0.025 = 0.05, +

+
+ + Standard + deviations either side of the Mean +
+

+ Armed with the cumulative distribution function, we can easily calculate + the easy to remember proportion of values that lie within 1, 2 and 3 + standard deviations from the mean. +

+
cout.precision(3);
+cout << showpoint << "cdf(s, s.standard_deviation()) = "
+  << cdf(s, s.standard_deviation()) << endl;  // from -infinity to 1 sd
+cout << "cdf(complement(s, s.standard_deviation())) = "
+  << cdf(complement(s, s.standard_deviation())) << endl;
+cout << "Fraction 1 standard deviation within either side of mean is "
+  << 1 -  cdf(complement(s, s.standard_deviation())) * 2 << endl;
+cout << "Fraction 2 standard deviations within either side of mean is "
+  << 1 -  cdf(complement(s, 2 * s.standard_deviation())) * 2 << endl;
+cout << "Fraction 3 standard deviations within either side of mean is "
+  << 1 -  cdf(complement(s, 3 * s.standard_deviation())) * 2 << endl;
+
+

+ To a useful precision, the 1, 2 & 3 percentages are 68, 95 and 99.7, + and these are worth memorising as useful 'rules of thumb', as, for example, + in standard + deviation: +

+
Fraction 1 standard deviation within either side of mean is 0.683
+Fraction 2 standard deviations within either side of mean is 0.954
+Fraction 3 standard deviations within either side of mean is 0.997
+
+

+ We could of course get some really accurate values for these confidence + intervals by using cout.precision(15); +

+
Fraction 1 standard deviation within either side of mean is 0.682689492137086
+Fraction 2 standard deviations within either side of mean is 0.954499736103642
+Fraction 3 standard deviations within either side of mean is 0.997300203936740
+
+

+ But before you get too excited about this impressive precision, don't + forget that the confidence intervals of the standard + deviation are surprisingly wide, especially if you have estimated + the standard deviation from only a few measurements. +

+
+ + Some + simple examples +
+
+ + Life + of light bulbs +
+

+ Examples from K. Krishnamoorthy, Handbook of Statistical Distributions + with Applications, ISBN 1 58488 635 8, page 125... implemented using + the Math Toolkit library. +

+

+ A few very simple examples are shown here: +

+
// K. Krishnamoorthy, Handbook of Statistical Distributions with Applications,
+ // ISBN 1 58488 635 8, page 125, example 10.3.5
+
+

+ Mean lifespan of 100 W bulbs is 1100 h with standard deviation of 100 + h. Assuming, perhaps with little evidence and much faith, that the distribution + is normal, we construct a normal distribution called bulbs + with these values: +

+
double mean_life = 1100.;
+double life_standard_deviation = 100.;
+normal bulbs(mean_life, life_standard_deviation);
+double expected_life = 1000.;
+
+

+ The we can use the Cumulative distribution function to predict fractions + (or percentages, if * 100) that will last various lifetimes. +

+
cout << "Fraction of bulbs that will last at best (<=) " // P(X <= 1000)
+  << expected_life << " is "<< cdf(bulbs, expected_life) << endl;
+cout << "Fraction of bulbs that will last at least (>) " // P(X > 1000)
+  << expected_life << " is "<< cdf(complement(bulbs, expected_life)) << endl;
+double min_life = 900;
+double max_life = 1200;
+cout << "Fraction of bulbs that will last between "
+  << min_life << " and " << max_life << " is "
+  << cdf(bulbs, max_life)  // P(X <= 1200)
+   - cdf(bulbs, min_life) << endl; // P(X <= 900)
+
+
+ + + + + +
[Note]Note

+ Real-life failures are often very ab-normal, with a significant number + that 'dead-on-arrival' or suffer failure very early in their life: + the lifetime of the survivors of 'early mortality' may be well described + by the normal distribution. +

+
+ + How + many onions? +
+

+ Weekly demand for 5 lb sacks of onions at a store is normally distributed + with mean 140 sacks and standard deviation 10. +

+
double mean = 140.; // sacks per week.
+double standard_deviation = 10;
+normal sacks(mean, standard_deviation);
+
+double stock = 160.; // per week.
+cout << "Percentage of weeks overstocked "
+  << cdf(sacks, stock) * 100. << endl; // P(X <=160)
+// Percentage of weeks overstocked 97.7
+
+

+ So there will be lots of mouldy onions! So we should be able to say what + stock level will meet demand 95% of the weeks. +

+
double stock_95 = quantile(sacks, 0.95);
+cout << "Store should stock " << int(stock_95) << " sacks to meet 95% of demands." << endl;
+
+

+ And it is easy to estimate how to meet 80% of demand, and waste even + less. +

+
double stock_80 = quantile(sacks, 0.80);
+cout << "Store should stock " << int(stock_80) << " sacks to meet 8 out of 10 demands." << endl;
+
+
+ + Packing + beef +
+

+ A machine is set to pack 3 kg of ground beef per pack. Over a long period + of time it is found that the average packed was 3 kg with a standard + deviation of 0.1 kg. Assuming the packing is normally distributed, we + can find the fraction (or %) of packages that weigh more than 3.1 kg. +

+
double mean = 3.; // kg
+double standard_deviation = 0.1; // kg
+normal packs(mean, standard_deviation);
+
+double max_weight = 3.1; // kg
+cout << "Percentage of packs > " << max_weight << " is "
+<< cdf(complement(packs, max_weight)) << endl; // P(X > 3.1)
+
+double under_weight = 2.9;
+cout <<"fraction of packs <= " << under_weight << " with a mean of " << mean
+  << " is " << cdf(complement(packs, under_weight)) << endl;
+// fraction of packs <= 2.9 with a mean of 3 is 0.841345
+// This is 0.84 - more than the target 0.95
+// Want 95% to be over this weight, so what should we set the mean weight to be?
+// KK StatCalc says:
+double over_mean = 3.0664;
+normal xpacks(over_mean, standard_deviation);
+cout << "fraction of packs >= " << under_weight
+<< " with a mean of " << xpacks.mean()
+  << " is " << cdf(complement(xpacks, under_weight)) << endl;
+// fraction of packs >= 2.9 with a mean of 3.06449 is 0.950005
+double under_fraction = 0.05;  // so 95% are above the minimum weight mean - sd = 2.9
+double low_limit = standard_deviation;
+double offset = mean - low_limit - quantile(packs, under_fraction);
+double nominal_mean = mean + offset;
+
+normal nominal_packs(nominal_mean, standard_deviation);
+cout << "Setting the packer to " << nominal_mean << " will mean that "
+  << "fraction of packs >= " << under_weight
+  << " is " << cdf(complement(nominal_packs, under_weight)) << endl;
+
+

+ Setting the packer to 3.06449 will mean that fraction of packs >= + 2.9 is 0.95. +

+

+ Setting the packer to 3.13263 will mean that fraction of packs >= + 2.9 is 0.99, but will more than double the mean loss from 0.0644 to 0.133. +

+

+ Alternatively, we could invest in a better (more precise) packer with + a lower standard deviation. +

+

+ To estimate how much better (how much smaller standard deviation) it + would have to be, we need to get the 5% quantile to be located at the + under_weight limit, 2.9 +

+
double p = 0.05; // wanted p th quantile.
+cout << "Quantile of " << p << " = " << quantile(packs, p)
+  << ", mean = " << packs.mean() << ", sd = " << packs.standard_deviation() << endl; //
+
+

+ Quantile of 0.05 = 2.83551, mean = 3, sd = 0.1 +

+

+ With the current packer (mean = 3, sd = 0.1), the 5% quantile is at 2.8551 + kg, a little below our target of 2.9 kg. So we know that the standard + deviation is going to have to be smaller. +

+

+ Let's start by guessing that it (now 0.1) needs to be halved, to a standard + deviation of 0.05 +

+
normal pack05(mean, 0.05);
+cout << "Quantile of " << p << " = " << quantile(pack05, p)
+  << ", mean = " << pack05.mean() << ", sd = " << pack05.standard_deviation() << endl;
+
+cout <<"Fraction of packs >= " << under_weight << " with a mean of " << mean
+  << " and standard deviation of " << pack05.standard_deviation()
+  << " is " << cdf(complement(pack05, under_weight)) << endl;
+//
+
+

+ Fraction of packs >= 2.9 with a mean of 3 and standard deviation of + 0.05 is 0.9772 +

+

+ So 0.05 was quite a good guess, but we are a little over the 2.9 target, + so the standard deviation could be a tiny bit more. So we could do some + more guessing to get closer, say by increasing to 0.06 +

+
normal pack06(mean, 0.06);
+cout << "Quantile of " << p << " = " << quantile(pack06, p)
+  << ", mean = " << pack06.mean() << ", sd = " << pack06.standard_deviation() << endl;
+
+cout <<"Fraction of packs >= " << under_weight << " with a mean of " << mean
+  << " and standard deviation of " << pack06.standard_deviation()
+  << " is " << cdf(complement(pack06, under_weight)) << endl;
+
+

+ Fraction of packs >= 2.9 with a mean of 3 and standard deviation of + 0.06 is 0.9522 +

+

+ Now we are getting really close, but to do the job properly, we could + use root finding method, for example the tools provided, and used elsewhere, + in the Math Toolkit, see root-finding + without derivatives. +

+

+ But in this normal distribution case, we could be even smarter and make + a direct calculation. +

+
normal s; // For standard normal distribution,
+double sd = 0.1;
+double x = 2.9; // Our required limit.
+// then probability p = N((x - mean) / sd)
+// So if we want to find the standard deviation that would be required to meet this limit,
+// so that the p th quantile is located at x,
+// in this case the 0.95 (95%) quantile at 2.9 kg pack weight, when the mean is 3 kg.
+
+double prob =  pdf(s, (x - mean) / sd);
+double qp = quantile(s, 0.95);
+cout << "prob = " << prob << ", quantile(p) " << qp << endl; // p = 0.241971, quantile(p) 1.64485
+// Rearranging, we can directly calculate the required standard deviation:
+double sd95 = std::abs((x - mean)) / qp;
+
+cout << "If we want the "<< p << " th quantile to be located at "
+  << x << ", would need a standard deviation of " << sd95 << endl;
+
+normal pack95(mean, sd95);  // Distribution of the 'ideal better' packer.
+cout <<"Fraction of packs >= " << under_weight << " with a mean of " << mean
+  << " and standard deviation of " << pack95.standard_deviation()
+  << " is " << cdf(complement(pack95, under_weight)) << endl;
+
+// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0608 is 0.95
+
+

+ Notice that these two deceptively simple questions (do we over-fill or + measure better) are actually very common. The weight of beef might be + replaced by a measurement of more or less anything. But the calculations + rely on the accuracy of the standard deviation - something that is almost + always less good than we might wish, especially if based on a few measurements. +

+
+ + Length + of bolts +
+

+ A bolt is usable if between 3.9 and 4.1 long. From a large batch of bolts, + a sample of 50 show a mean length of 3.95 with standard deviation 0.1. + Assuming a normal distribution, what proportion is usable? The true sample + mean is unknown, but we can use the sample mean and standard deviation + to find approximate solutions. +

+
    normal bolts(3.95, 0.1);
+    double top = 4.1;
+    double bottom = 3.9;
+
+cout << "Fraction long enough [ P(X <= " << top << ") ] is " << cdf(bolts, top) << endl;
+cout << "Fraction too short [ P(X <= " << bottom << ") ] is " << cdf(bolts, bottom) << endl;
+cout << "Fraction OK  -between " << bottom << " and " << top
+  << "[ P(X <= " << top  << ") - P(X<= " << bottom << " ) ] is "
+  << cdf(bolts, top) - cdf(bolts, bottom) << endl;
+
+cout << "Fraction too long [ P(X > " << top << ") ] is "
+  << cdf(complement(bolts, top)) << endl;
+
+cout << "95% of bolts are shorter than " << quantile(bolts, 0.95) << endl;
+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg.html new file mode 100644 index 00000000..f12eccb9 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg.html @@ -0,0 +1,60 @@ + + + +Student's t Distribution Examples + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ + +
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/paired_st.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/paired_st.html new file mode 100644 index 00000000..c1e97eeb --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/paired_st.html @@ -0,0 +1,81 @@ + + + +Comparing two paired samples with the Student's t distribution + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Imagine that we have a before and after reading for each item in the + sample: for example we might have measured blood pressure before and + after administration of a new drug. We can't pool the results and compare + the means before and after the change, because each patient will have + a different baseline reading. Instead we calculate the difference between + before and after measurements in each patient, and calculate the mean + and standard deviation of the differences. To test whether a significant + change has taken place, we can then test the null-hypothesis that the + true mean is zero using the same procedure we used in the single sample + cases previously discussed. +

+

+ That means we can: +

+
+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_intervals.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_intervals.html new file mode 100644 index 00000000..4ccaf10c --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_intervals.html @@ -0,0 +1,267 @@ + + + +Calculating confidence intervals on the mean with the Students-t distribution + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Let's say you have a sample mean, you may wish to know what confidence + intervals you can place on that mean. Colloquially: "I want an interval + that I can be P% sure contains the true mean". (On a technical point, + note that the interval either contains the true mean or it does not: + the meaning of the confidence level is subtly different from this colloquialism. + More background information can be found on the NIST + site). +

+

+ The formula for the interval can be expressed as: +

+

+ +

+

+ Where, Ys is the sample mean, s + is the sample standard deviation, N is the sample + size, /α/ is the desired significance level and t(α/2,N-1) + is the upper critical value of the Students-t distribution with N-1 + degrees of freedom. +

+
+ + + + + +
[Note]Note
+

+ The quantity α   is the maximum acceptable risk of falsely rejecting the + null-hypothesis. The smaller the value of α the greater the strength + of the test. +

+

+ The confidence level of the test is defined as 1 - α, and often expressed + as a percentage. So for example a significance level of 0.05, is equivalent + to a 95% confidence level. Refer to "What + are confidence intervals?" in NIST/SEMATECH + e-Handbook of Statistical Methods. for more information. +

+
+
+ + + + + +
[Note]Note

+ The usual assumptions of independent + and identically distributed (i.i.d.) variables and normal + distribution of course apply here, as they do in other examples. +

+

+ From the formula, it should be clear that: +

+
    +
  • + The width of the confidence interval decreases as the sample size + increases. +
  • +
  • + The width increases as the standard deviation increases. +
  • +
  • + The width increases as the confidence level increases + (0.5 towards 0.99999 - stronger). +
  • +
  • + The width increases as the significance level decreases + (0.5 towards 0.00000...01 - stronger). +
  • +
+

+ The following example code is taken from the example program students_t_single_sample.cpp. +

+

+ We'll begin by defining a procedure to calculate intervals for various + confidence levels; the procedure will print these out as a table: +

+
// Needed includes:
+#include <boost/math/distributions/students_t.hpp>
+#include <iostream>
+#include <iomanip>
+// Bring everything into global namespace for ease of use:
+using namespace boost::math;
+using namespace std;
+
+void confidence_limits_on_mean(
+   double Sm,           // Sm = Sample Mean.
+   double Sd,           // Sd = Sample Standard Deviation.
+   unsigned Sn)         // Sn = Sample Size.
+{
+   using namespace std;
+   using namespace boost::math;
+
+   // Print out general info:
+   cout <<
+      "__________________________________\n"
+      "2-Sided Confidence Limits For Mean\n"
+      "__________________________________\n\n";
+   cout << setprecision(7);
+   cout << setw(40) << left << "Number of Observations" << "=  " << Sn << "\n";
+   cout << setw(40) << left << "Mean" << "=  " << Sm << "\n";
+   cout << setw(40) << left << "Standard Deviation" << "=  " << Sd << "\n";
+
+

+ We'll define a table of significance/risk levels for which we'll compute + intervals: +

+
double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
+
+

+ Note that these are the complements of the confidence/probability levels: + 0.5, 0.75, 0.9 .. 0.99999). +

+

+ Next we'll declare the distribution object we'll need, note that the + degrees of freedom parameter is the sample size + less one: +

+
students_t dist(Sn - 1);
+
+

+ Most of what follows in the program is pretty printing, so let's focus + on the calculation of the interval. First we need the t-statistic, computed + using the quantile function and our significance + level. Note that since the significance levels are the complement of + the probability, we have to wrap the arguments in a call to complement(...): +

+
double T = quantile(complement(dist, alpha[i] / 2));
+
+

+ Note that alpha was divided by two, since we'll be calculating both the + upper and lower bounds: had we been interested in a single sided interval + then we would have omitted this step. +

+

+ Now to complete the picture, we'll get the (one-sided) width of the interval + from the t-statistic by multiplying by the standard deviation, and dividing + by the square root of the sample size: +

+
double w = T * Sd / sqrt(double(Sn));
+
+

+ The two-sided interval is then the sample mean plus and minus this width. +

+

+ And apart from some more pretty-printing that completes the procedure. +

+

+ Let's take a look at some sample output, first using the Heat + flow data from the NIST site. The data set was collected by Bob + Zarr of NIST in January, 1990 from a heat flow meter calibration and + stability analysis. The corresponding dataplot output for this test can + be found in section + 3.5.2 of the NIST/SEMATECH + e-Handbook of Statistical Methods.. +

+
   __________________________________
+   2-Sided Confidence Limits For Mean
+   __________________________________
+
+   Number of Observations                  =  195
+   Mean                                    =  9.26146
+   Standard Deviation                      =  0.02278881
+
+
+   ___________________________________________________________________
+   Confidence       T           Interval          Lower          Upper
+    Value (%)     Value          Width            Limit          Limit
+   ___________________________________________________________________
+       50.000     0.676       1.103e-003        9.26036        9.26256
+       75.000     1.154       1.883e-003        9.25958        9.26334
+       90.000     1.653       2.697e-003        9.25876        9.26416
+       95.000     1.972       3.219e-003        9.25824        9.26468
+       99.000     2.601       4.245e-003        9.25721        9.26571
+       99.900     3.341       5.453e-003        9.25601        9.26691
+       99.990     3.973       6.484e-003        9.25498        9.26794
+       99.999     4.537       7.404e-003        9.25406        9.26886
+
+

+ As you can see the large sample size (195) and small standard deviation + (0.023) have combined to give very small intervals, indeed we can be + very confident that the true mean is 9.2. +

+

+ For comparison the next example data output is taken from P.K.Hou, + O. W. Lau & M.C. Wong, Analyst (1983) vol. 108, p 64. and from Statistics + for Analytical Chemistry, 3rd ed. (1994), pp 54-55 J. C. Miller and J. + N. Miller, Ellis Horwood ISBN 0 13 0309907. The values result + from the determination of mercury by cold-vapour atomic absorption. +

+
   __________________________________
+   2-Sided Confidence Limits For Mean
+   __________________________________
+
+   Number of Observations                  =  3
+   Mean                                    =  37.8000000
+   Standard Deviation                      =  0.9643650
+
+
+   ___________________________________________________________________
+   Confidence       T           Interval          Lower          Upper
+    Value (%)     Value          Width            Limit          Limit
+   ___________________________________________________________________
+       50.000     0.816            0.455       37.34539       38.25461
+       75.000     1.604            0.893       36.90717       38.69283
+       90.000     2.920            1.626       36.17422       39.42578
+       95.000     4.303            2.396       35.40438       40.19562
+       99.000     9.925            5.526       32.27408       43.32592
+       99.900    31.599           17.594       20.20639       55.39361
+       99.990    99.992           55.673      -17.87346       93.47346
+       99.999   316.225          176.067     -138.26683      213.86683
+
+

+ This time the fact that there are only three measurements leads to much + wider intervals, indeed such large intervals that it's hard to be very + confident in the location of the mean. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_size.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_size.html new file mode 100644 index 00000000..fe8336ad --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_size.html @@ -0,0 +1,179 @@ + + + +Estimating how large a sample size would have to become in order to give a significant Students-t test result with a single sample test + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Imagine you have conducted a Students-t test on a single sample in order + to check for systematic errors in your measurements. Imagine that the + result is borderline. At this point one might go off and collect more + data, but it might be prudent to first ask the question "How much + more?". The parameter estimators of the students_t_distribution + class can provide this information. +

+

+ This section is based on the example code in students_t_single_sample.cpp + and we begin by defining a procedure that will print out a table of estimated + sample sizes for various confidence levels: +

+
// Needed includes:
+#include <boost/math/distributions/students_t.hpp>
+#include <iostream>
+#include <iomanip>
+// Bring everything into global namespace for ease of use:
+using namespace boost::math;
+using namespace std;
+
+void single_sample_find_df(
+   double M,          // M = true mean.
+   double Sm,         // Sm = Sample Mean.
+   double Sd)         // Sd = Sample Standard Deviation.
+{
+
+

+ Next we define a table of significance levels: +

+
double alpha[] = { 0.5, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
+
+

+ Printing out the table of sample sizes required for various confidence + levels begins with the table header: +

+
cout << "\n\n"
+        "_______________________________________________________________\n"
+        "Confidence       Estimated          Estimated\n"
+        " Value (%)      Sample Size        Sample Size\n"
+        "              (one sided test)    (two sided test)\n"
+        "_______________________________________________________________\n";
+
+

+ And now the important part: the sample sizes required. Class students_t_distribution has a static + member function find_degrees_of_freedom + that will calculate how large a sample size needs to be in order to give + a definitive result. +

+

+ The first argument is the difference between the means that you wish + to be able to detect, here it's the absolute value of the difference + between the sample mean, and the true mean. +

+

+ Then come two probability values: alpha and beta. Alpha is the maximum + acceptable risk of rejecting the null-hypothesis when it is in fact true. + Beta is the maximum acceptable risk of failing to reject the null-hypothesis + when in fact it is false. Also note that for a two-sided test, alpha + must be divided by 2. +

+

+ The final parameter of the function is the standard deviation of the + sample. +

+

+ In this example, we assume that alpha and beta are the same, and call + find_degrees_of_freedom + twice: once with alpha for a one-sided test, and once with alpha/2 for + a two-sided test. +

+
   for(unsigned i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)
+   {
+      // Confidence value:
+      cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]);
+      // calculate df for single sided test:
+      double df = students_t::find_degrees_of_freedom(
+         fabs(M - Sm), alpha[i], alpha[i], Sd);
+      // convert to sample size:
+      double size = ceil(df) + 1;
+      // Print size:
+      cout << fixed << setprecision(0) << setw(16) << right << size;
+      // calculate df for two sided test:
+      df = students_t::find_degrees_of_freedom(
+         fabs(M - Sm), alpha[i]/2, alpha[i], Sd);
+      // convert to sample size:
+      size = ceil(df) + 1;
+      // Print size:
+      cout << fixed << setprecision(0) << setw(16) << right << size << endl;
+   }
+   cout << endl;
+}
+
+

+ Let's now look at some sample output using data taken from P.K.Hou, + O. W. Lau & M.C. Wong, Analyst (1983) vol. 108, p 64. and from Statistics + for Analytical Chemistry, 3rd ed. (1994), pp 54-55 J. C. Miller and J. + N. Miller, Ellis Horwood ISBN 0 13 0309907. The values result + from the determination of mercury by cold-vapour atomic absorption. +

+

+ Only three measurements were made, and the Students-t test above gave + a borderline result, so this example will show us how many samples would + need to be collected: +

+
_____________________________________________________________
+Estimated sample sizes required for various confidence levels
+_____________________________________________________________
+
+True Mean                               =  38.90000
+Sample Mean                             =  37.80000
+Sample Standard Deviation               =  0.96437
+
+
+_______________________________________________________________
+Confidence       Estimated          Estimated
+ Value (%)      Sample Size        Sample Size
+              (one sided test)    (two sided test)
+_______________________________________________________________
+    75.000               3               4
+    90.000               7               9
+    95.000              11              13
+    99.000              20              22
+    99.900              35              37
+    99.990              50              53
+    99.999              66              68
+
+

+ So in this case, many more measurements would have had to be made, for + example at the 95% level, 14 measurements in total for a two-sided test. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_test.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_test.html new file mode 100644 index 00000000..7939f776 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/tut_mean_test.html @@ -0,0 +1,334 @@ + + + +Testing a sample mean for difference from a "true" mean + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ When calibrating or comparing a scientific instrument or measurement + method of some kind, we want to be answer the question "Does an + observed sample mean differ from the "true" mean in any significant + way?". If it does, then we have evidence of a systematic difference. + This question can be answered with a Students-t test: more information + can be found on + the NIST site. +

+

+ Of course, the assignment of "true" to one mean may be quite + arbitrary, often this is simply a "traditional" method of measurement. +

+

+ The following example code is taken from the example program students_t_single_sample.cpp. +

+

+ We'll begin by defining a procedure to determine which of the possible + hypothesis are rejected or not-rejected at a given significance level: +

+
+ + + + + +
[Note]Note

+ Non-statisticians might say 'not-rejected' means 'accepted', (often + of the null-hypothesis) implying, wrongly, that there really IS no difference, but statisticans eschew this + to avoid implying that there is positive evidence of 'no difference'. + 'Not-rejected' here means there is no evidence + of difference, but there still might well be a difference. For example, + see argument + from ignorance and Absence + of evidence does not constitute evidence of absence. +

+
// Needed includes:
+#include <boost/math/distributions/students_t.hpp>
+#include <iostream>
+#include <iomanip>
+// Bring everything into global namespace for ease of use:
+using namespace boost::math;
+using namespace std;
+
+void single_sample_t_test(double M, double Sm, double Sd, unsigned Sn, double alpha)
+{
+   //
+   // M = true mean.
+   // Sm = Sample Mean.
+   // Sd = Sample Standard Deviation.
+   // Sn = Sample Size.
+   // alpha = Significance Level.
+
+

+ Most of the procedure is pretty-printing, so let's just focus on the + calculation, we begin by calculating the t-statistic: +

+
// Difference in means:
+double diff = Sm - M;
+// Degrees of freedom:
+unsigned v = Sn - 1;
+// t-statistic:
+double t_stat = diff * sqrt(double(Sn)) / Sd;
+
+

+ Finally calculate the probability from the t-statistic. If we're interested + in simply whether there is a difference (either less or greater) or not, + we don't care about the sign of the t-statistic, and we take the complement + of the probability for comparison to the significance level: +

+
students_t dist(v);
+double q = cdf(complement(dist, fabs(t_stat)));
+
+

+ The procedure then prints out the results of the various tests that can + be done, these can be summarised in the following table: +

+
++++ + + + + + + + + + + + + + + + + + + + + + + +
+

+ Hypothesis +

+
+

+ Test +

+
+

+ The Null-hypothesis: there is no difference + in means +

+
+

+ Reject if complement of CDF for |t| < significance level + / 2: +

+

+ cdf(complement(dist, + fabs(t))) + < alpha + / 2 +

+
+

+ The Alternative-hypothesis: there is + difference in means +

+
+

+ Reject if complement of CDF for |t| > significance level + / 2: +

+

+ cdf(complement(dist, + fabs(t))) + > alpha + / 2 +

+
+

+ The Alternative-hypothesis: the sample mean is + less than the true mean. +

+
+

+ Reject if CDF of t > 1 - significance level: +

+

+ cdf(complement(dist, + t)) + < alpha +

+
+

+ The Alternative-hypothesis: the sample mean is + greater than the true mean. +

+
+

+ Reject if complement of CDF of t < significance level: +

+

+ cdf(dist, + t) + < alpha +

+
+
+ + + + + +
[Note]Note

+ Notice that the comparisons are against alpha + / 2 + for a two-sided test and against alpha + for a one-sided test +

+

+ Now that we have all the parts in place, let's take a look at some sample + output, first using the Heat + flow data from the NIST site. The data set was collected by Bob + Zarr of NIST in January, 1990 from a heat flow meter calibration and + stability analysis. The corresponding dataplot output for this test can + be found in section + 3.5.2 of the NIST/SEMATECH + e-Handbook of Statistical Methods.. +

+
__________________________________
+Student t test for a single sample
+__________________________________
+
+Number of Observations                                 =  195
+Sample Mean                                            =  9.26146
+Sample Standard Deviation                              =  0.02279
+Expected True Mean                                     =  5.00000
+
+Sample Mean - Expected Test Mean                       =  4.26146
+Degrees of Freedom                                     =  194
+T Statistic                                            =  2611.28380
+Probability that difference is due to chance           =  0.000e+000
+
+Results for Alternative Hypothesis and alpha           =  0.0500
+
+Alternative Hypothesis     Conclusion
+Mean != 5.000            NOT REJECTED
+Mean  < 5.000            REJECTED
+Mean  > 5.000            NOT REJECTED
+
+

+ You will note the line that says the probability that the difference + is due to chance is zero. From a philosophical point of view, of course, + the probability can never reach zero. However, in this case the calculated + probability is smaller than the smallest representable double precision + number, hence the appearance of a zero here. Whatever its "true" + value is, we know it must be extraordinarily small, so the alternative + hypothesis - that there is a difference in means - is not rejected. +

+

+ For comparison the next example data output is taken from P.K.Hou, + O. W. Lau & M.C. Wong, Analyst (1983) vol. 108, p 64. and from Statistics + for Analytical Chemistry, 3rd ed. (1994), pp 54-55 J. C. Miller and J. + N. Miller, Ellis Horwood ISBN 0 13 0309907. The values result + from the determination of mercury by cold-vapour atomic absorption. +

+
__________________________________
+Student t test for a single sample
+__________________________________
+
+Number of Observations                                 =  3
+Sample Mean                                            =  37.80000
+Sample Standard Deviation                              =  0.96437
+Expected True Mean                                     =  38.90000
+
+Sample Mean - Expected Test Mean                       =  -1.10000
+Degrees of Freedom                                     =  2
+T Statistic                                            =  -1.97566
+Probability that difference is due to chance           =  1.869e-001
+
+Results for Alternative Hypothesis and alpha           =  0.0500
+
+Alternative Hypothesis     Conclusion
+Mean != 38.900            REJECTED
+Mean  < 38.900            NOT REJECTED
+Mean  > 38.900            NOT REJECTED
+
+

+ As you can see the small number of measurements (3) has led to a large + uncertainty in the location of the true mean. So even though there appears + to be a difference between the sample mean and the expected true mean, + we conclude that there is no significant difference, and are unable to + reject the null hypothesis. However, if we were to lower the bar for + acceptance down to alpha = 0.1 (a 90% confidence level) we see a different + output: +

+
__________________________________
+Student t test for a single sample
+__________________________________
+
+Number of Observations                                 =  3
+Sample Mean                                            =  37.80000
+Sample Standard Deviation                              =  0.96437
+Expected True Mean                                     =  38.90000
+
+Sample Mean - Expected Test Mean                       =  -1.10000
+Degrees of Freedom                                     =  2
+T Statistic                                            =  -1.97566
+Probability that difference is due to chance           =  1.869e-001
+
+Results for Alternative Hypothesis and alpha           =  0.1000
+
+Alternative Hypothesis     Conclusion
+Mean != 38.900            REJECTED
+Mean  < 38.900            NOT REJECTED
+Mean  > 38.900            REJECTED
+
+

+ In this case, we really have a borderline result, and more data (and/or + more accurate data), is needed for a more convincing conclusion. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + diff --git a/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/two_sample_students_t.html b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/two_sample_students_t.html new file mode 100644 index 00000000..9d35bcf6 --- /dev/null +++ b/boost/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/two_sample_students_t.html @@ -0,0 +1,359 @@ + + + +Comparing the means of two samples with the Students-t test + + + + + + + + + + + + + + + +
Boost C++ LibrariesHomeLibrariesPeopleFAQMore
+
+
+PrevUpHomeNext +
+
+ +

+ Imagine that we have two samples, and we wish to determine whether their + means are different or not. This situation often arises when determining + whether a new process or treatment is better than an old one. +

+

+ In this example, we'll be using the Car + Mileage sample data from the NIST + website. The data compares miles per gallon of US cars with miles + per gallon of Japanese cars. +

+

+ The sample code is in students_t_two_samples.cpp. +

+

+ There are two ways in which this test can be conducted: we can assume + that the true standard deviations of the two samples are equal or not. + If the standard deviations are assumed to be equal, then the calculation + of the t-statistic is greatly simplified, so we'll examine that case + first. In real life we should verify whether this assumption is valid + with a Chi-Squared test for equal variances. +

+

+ We begin by defining a procedure that will conduct our test assuming + equal variances: +

+
// Needed headers:
+#include <boost/math/distributions/students_t.hpp>
+#include <iostream>
+#include <iomanip>
+// Simplify usage:
+using namespace boost::math;
+using namespace std;
+
+void two_samples_t_test_equal_sd(
+        double Sm1,       // Sm1 = Sample 1 Mean.
+        double Sd1,       // Sd1 = Sample 1 Standard Deviation.
+        unsigned Sn1,     // Sn1 = Sample 1 Size.
+        double Sm2,       // Sm2 = Sample 2 Mean.
+        double Sd2,       // Sd2 = Sample 2 Standard Deviation.
+        unsigned Sn2,     // Sn2 = Sample 2 Size.
+        double alpha)     // alpha = Significance Level.
+{
+
+

+ Our procedure will begin by calculating the t-statistic, assuming equal + variances the needed formulae are: +

+

+ +

+

+ where Sp is the "pooled" standard deviation of the two samples, + and v is the number of degrees of freedom of the + two combined samples. We can now write the code to calculate the t-statistic: +

+
// Degrees of freedom:
+double v = Sn1 + Sn2 - 2;
+cout << setw(55) << left << "Degrees of Freedom" << "=  " << v << "\n";
+// Pooled variance:
+double sp = sqrt(((Sn1-1) * Sd1 * Sd1 + (Sn2-1) * Sd2 * Sd2) / v);
+cout << setw(55) << left << "Pooled Standard Deviation" << "=  " << sp << "\n";
+// t-statistic:
+double t_stat = (Sm1 - Sm2) / (sp * sqrt(1.0 / Sn1 + 1.0 / Sn2));
+cout << setw(55) << left << "T Statistic" << "=  " << t_stat << "\n";
+
+

+ The next step is to define our distribution object, and calculate the + complement of the probability: +

+
students_t dist(v);
+double q = cdf(complement(dist, fabs(t_stat)));
+cout << setw(55) << left << "Probability that difference is due to chance" << "=  "
+   << setprecision(3) << scientific << 2 * q << "\n\n";
+
+

+ Here we've used the absolute value of the t-statistic, because we initially + want to know simply whether there is a difference or not (a two-sided + test). However, we can also test whether the mean of the second sample + is greater or is less (one-sided test) than that of the first: all the + possible tests are summed up in the following table: +

+
++++ + + + + + + + + + + + + + + + + + + + + + + +
+

+ Hypothesis +

+
+

+ Test +

+
+

+ The Null-hypothesis: there is no difference + in means +

+
+

+ Reject if complement of CDF for |t| < significance level + / 2: +

+

+ cdf(complement(dist, + fabs(t))) + < alpha + / 2 +

+
+

+ The Alternative-hypothesis: there is a difference + in means +

+
+

+ Reject if complement of CDF for |t| > significance level + / 2: +

+

+ cdf(complement(dist, + fabs(t))) + < alpha + / 2 +

+
+

+ The Alternative-hypothesis: Sample 1 Mean is less + than Sample 2 Mean. +

+
+

+ Reject if CDF of t > significance level: +

+

+ cdf(dist, + t) + > alpha +

+
+

+ The Alternative-hypothesis: Sample 1 Mean is greater + than Sample 2 Mean. +

+
+

+ Reject if complement of CDF of t > significance level: +

+

+ cdf(complement(dist, + t)) + > alpha +

+
+
+ + + + + +
[Note]Note

+ For a two-sided test we must compare against alpha / 2 and not alpha. +

+

+ Most of the rest of the sample program is pretty-printing, so we'll skip + over that, and take a look at the sample output for alpha=0.05 (a 95% + probability level). For comparison the dataplot output for the same data + is in section + 1.3.5.3 of the NIST/SEMATECH + e-Handbook of Statistical Methods.. +

+
   ________________________________________________
+   Student t test for two samples (equal variances)
+   ________________________________________________
+
+   Number of Observations (Sample 1)                      =  249
+   Sample 1 Mean                                          =  20.145
+   Sample 1 Standard Deviation                            =  6.4147
+   Number of Observations (Sample 2)                      =  79
+   Sample 2 Mean                                          =  30.481
+   Sample 2 Standard Deviation                            =  6.1077
+   Degrees of Freedom                                     =  326
+   Pooled Standard Deviation                              =  6.3426
+   T Statistic                                            =  -12.621
+   Probability that difference is due to chance           =  5.273e-030
+
+   Results for Alternative Hypothesis and alpha           =  0.0500
+
+   Alternative Hypothesis              Conclusion
+   Sample 1 Mean != Sample 2 Mean       NOT REJECTED
+   Sample 1 Mean <  Sample 2 Mean       NOT REJECTED
+   Sample 1 Mean >  Sample 2 Mean       REJECTED
+
+

+ So with a probability that the difference is due to chance of just 5.273e-030, + we can safely conclude that there is indeed a difference. +

+

+ The tests on the alternative hypothesis show that we must also reject + the hypothesis that Sample 1 Mean is greater than that for Sample 2: + in this case Sample 1 represents the miles per gallon for Japanese cars, + and Sample 2 the miles per gallon for US cars, so we conclude that Japanese + cars are on average more fuel efficient. +

+

+ Now that we have the simple case out of the way, let's look for a moment + at the more complex one: that the standard deviations of the two samples + are not equal. In this case the formula for the t-statistic becomes: +

+

+ +

+

+ And for the combined degrees of freedom we use the Welch-Satterthwaite + approximation: +

+

+ +

+

+ Note that this is one of the rare situations where the degrees-of-freedom + parameter to the Student's t distribution is a real number, and not an + integer value. +

+
+ + + + + +
[Note]Note

+ Some statistical packages truncate the effective degrees of freedom + to an integer value: this may be necessary if you are relying on lookup + tables, but since our code fully supports non-integer degrees of freedom + there is no need to truncate in this case. Also note that when the + degrees of freedom is small then the Welch-Satterthwaite approximation + may be a significant source of error. +

+

+ Putting these formulae into code we get: +

+
// Degrees of freedom:
+double v = Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2;
+v *= v;
+double t1 = Sd1 * Sd1 / Sn1;
+t1 *= t1;
+t1 /=  (Sn1 - 1);
+double t2 = Sd2 * Sd2 / Sn2;
+t2 *= t2;
+t2 /= (Sn2 - 1);
+v /= (t1 + t2);
+cout << setw(55) << left << "Degrees of Freedom" << "=  " << v << "\n";
+// t-statistic:
+double t_stat = (Sm1 - Sm2) / sqrt(Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2);
+cout << setw(55) << left << "T Statistic" << "=  " << t_stat << "\n";
+
+

+ Thereafter the code and the tests are performed the same as before. Using + are car mileage data again, here's what the output looks like: +

+
   __________________________________________________
+   Student t test for two samples (unequal variances)
+   __________________________________________________
+
+   Number of Observations (Sample 1)                      =  249
+   Sample 1 Mean                                          =  20.145
+   Sample 1 Standard Deviation                            =  6.4147
+   Number of Observations (Sample 2)                      =  79
+   Sample 2 Mean                                          =  30.481
+   Sample 2 Standard Deviation                            =  6.1077
+   Degrees of Freedom                                     =  136.87
+   T Statistic                                            =  -12.946
+   Probability that difference is due to chance           =  1.571e-025
+
+   Results for Alternative Hypothesis and alpha           =  0.0500
+
+   Alternative Hypothesis              Conclusion
+   Sample 1 Mean != Sample 2 Mean       NOT REJECTED
+   Sample 1 Mean <  Sample 2 Mean       NOT REJECTED
+   Sample 1 Mean >  Sample 2 Mean       REJECTED
+
+

+ This time allowing the variances in the two samples to differ has yielded + a higher likelihood that the observed difference is down to chance alone + (1.571e-025 compared to 5.273e-030 when equal variances were assumed). + However, the conclusion remains the same: US cars are less fuel efficient + than Japanese models. +

+
+ + + +
+
+
+PrevUpHomeNext +
+ + -- cgit v1.2.3