2
0
mirror of https://github.com/boostorg/math.git synced 2026-01-19 04:22:09 +00:00

Changed to avoid using namespace boost::math

[SVN r65665]
This commit is contained in:
Paul A. Bristow
2010-09-29 10:32:55 +00:00
parent 7050b81300
commit be4bd91753
15 changed files with 98 additions and 175 deletions

View File

@@ -1,91 +0,0 @@
// Copyright Paul A. 2006
// Copyright John Maddock 2006
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
// Simple example of computing probabilities for a binomial random variable.
// Replication of source nag_binomial_dist (g01bjc).
// Shows how to replace NAG C library calls by Boost Math Toolkit C++ calls.
#ifdef _MSC_VER
# pragma warning(disable: 4512) // assignment operator could not be generated.
# pragma warning(disable: 4510) // default constructor could not be generated.
# pragma warning(disable: 4610) // can never be instantiated - user defined constructor required.
#endif
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
using std::showpoint;
#include <iomanip>
using std::fixed;
using std::setw;
#include <boost/math/distributions/binomial.hpp>
int main()
{
cout << "Example 3 of using the binomial distribution to replicate a NAG library call." << endl;
using boost::math::binomial_distribution;
// This replicates the computation of the examples of using nag-binomial_dist
// using g01bjc in section g01 Sample Calculations on Statistical Data.
// http://www.nag.co.uk/numeric/cl/manual/pdf/G01/g01bjc.pdf
// Program results section 8.3 page 3.g01bjc.3
//8.2. Program Data
//g01bjc Example Program Data
//4 0.50 2 : n, p, k
//19 0.44 13
//100 0.75 67
//2000 0.33 700
//8.3. Program Results
//g01bjc Example Program Results
//n p k plek pgtk peqk
//4 0.500 2 0.68750 0.31250 0.37500
//19 0.440 13 0.99138 0.00862 0.01939
//100 0.750 67 0.04460 0.95540 0.01700
//2000 0.330 700 0.97251 0.02749 0.00312
cout.setf(ios::showpoint); // Trailing zeros to show significant decimal digits.
cout.precision(5); // Should be able to calculate this?
cout << fixed;
// Binomial distribution.
// Note that cdf(dist, k) is equivalent to NAG library plek probability of <= k
// cdf(complement(dist, k)) is equivalent to NAG library pgtk probability of > k
// pdf(dist, k) is equivalent to NAG library peqk probability of == k
cout << " n p k plek pgtk peqk " << endl;
binomial_distribution<>my_dist(4, 0.5);
cout << setw(4) << (int)my_dist.trials() << " " << my_dist.success_fraction() << " "<< 2 << " "
<< cdf(my_dist, 2) << " " << cdf(complement(my_dist, 2)) << " " << pdf(my_dist, 2) << endl;
binomial_distribution<>two(19, 0.440);
cout << setw(4) << (int)two.trials() << " " << two.success_fraction() << " " << 13 << " "
<< cdf(two, 13) << " " << cdf(complement(two, 13)) << " " << pdf(two, 13) << endl;
binomial_distribution<>three(100, 0.750);
cout << setw(4) << (int)three.trials() << " " << three.success_fraction() << " " << 67 << " "
<< cdf(three, 67) << " " << cdf(complement(three, 67)) << " " << pdf(three, 67) << endl;
binomial_distribution<>four(2000, 0.330);
cout << setw(4) << (int)four.trials() << " " << four.success_fraction() << " " << 700 << " "
<< cdf(four, 700) << " " << cdf(complement(four, 700)) << " " << pdf(four, 700) << endl;
return 0;
} // int main()
/*
Autorun "i:\boost-sandbox\math_toolkit\libs\math\test\msvc80\debug\binomial_example3.exe"
Example 3 of using the binomial distribution.
n p k plek pgtk peqk
4 0.50000 2 0.68750 0.31250 0.37500
19 0.44000 13 0.99138 0.00862 0.01939
100 0.75000 67 0.04460 0.95540 0.01700
2000 0.33000 700 0.97251 0.02749 0.00312
*/

View File

@@ -11,6 +11,8 @@
// Suppose we want a call to tgamma to behave in a C-compatible way
// and set global ::errno rather than throw an exception.
#include <cerrno> // for ::errno
#include <boost/math/special_functions/gamma.hpp>
using boost::math::tgamma;
@@ -58,7 +60,7 @@ int main()
overflow_error<errno_on_error>(),
evaluation_error<errno_on_error>()
));
cout << "tgamma(4., make_policy( ...) = " << t << endl; // 6
cout << "tgamma(4., make_policy(...) = " << t << endl; // 6
return 0;
} // int main()
@@ -72,8 +74,8 @@ Output
Finished generating code
c_error_policy_example.vcxproj -> J:\Cpp\MathToolkit\test\Math_test\Release\c_error_policy_example.exe
tgamma(4., C_error_policy() = 6
tgamma(4., make_policy( ...) = 6
tgamma(4., make_policy(...) = 6
tgamma(4., C_error_policy() = 6
tgamma(4., make_policy( ...) = 6
tgamma(4., make_policy(...) = 6
*/

View File

@@ -76,10 +76,10 @@ void confidence_limits_on_std_deviation(
void confidence_limits_on_std_deviation_alpha(
double Sd, // Sample Standard Deviation
double alpha // confidence
)
double alpha // confidence
)
{ // Calculate confidence intervals for the standard deviation.
// for the alpha parameter, for a range number of observations,
// for the alpha parameter, for a range number of observations,
// from a mere 2 up to a million.
// O. L. Davies, Statistical Methods in Research and Production, ISBN 0 05 002437 X,
// 4.33 Page 68, Table H, pp 452 459.
@@ -111,7 +111,7 @@ void confidence_limits_on_std_deviation_alpha(
unsigned int N = obs[i]; // Observations
// Start by declaring the distribution with the appropriate :
chi_squared dist(N - 1);
// Now print out the data for the table row.
cout << fixed << setprecision(3) << setw(10) << right << N;
// Calculate limits: (alpha /2 because it is a two-sided (upper and lower limit) test.
@@ -244,17 +244,17 @@ void chi_squared_sample_sized(
{
// Confidence value:
cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]);
// calculate df for a lower single-sided test:
// 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:
// Convert to integral sample size (df is a floating point value in this implementation):
double size = ceil(df) + 1;
// Print size:
cout << fixed << setprecision(0) << setw(16) << right << size;
// calculate df for an upper single-sided test:
// 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:
// Convert to integral sample size:
size = ceil(df) + 1;
// Print size:
cout << fixed << setprecision(0) << setw(16) << right << size << endl;

View File

@@ -42,7 +42,7 @@ Several examples of constructing distributions follow:
int main()
{
//[distribution_construction2
/*`
/*`
First, a negative binomial distribution with 8 successes
and a success fraction 0.25, 25% or 1 in 4, is constructed like this:
*/
@@ -50,10 +50,10 @@ and a success fraction 0.25, 25% or 1 in 4, is constructed like this:
/*`
But this is inconveniently long, so we might be tempted to write
*/
using namespace boost::math;
using namespace boost::math;
/*`
but this might risk ambiguity with names in std random so *much better* is
explicit 'using boost::math:: ' ... statements like
but this might risk ambiguity with names in std random so
*much better is explicit `using boost::math:: ` * ... statements like
*/
using boost::math::negative_binomial_distribution;
/*`
@@ -73,7 +73,7 @@ and a success fraction 0.25, 25% or 1 in 4, is constructed like this:
typedef negative_binomial_distribution<double> negative_binomial; // Reserved name of type double.
[caution
This convenience typedef is /not/ provided if a clash would occur
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.
]
@@ -82,7 +82,7 @@ and a success fraction 0.25, 25% or 1 in 4, is constructed like this:
*/
using boost::math::negative_binomial;
/*`
we have a convenient typedef to `negative_binomial_distribution<double>`:
*/
@@ -111,7 +111,7 @@ and a success fraction 0.25, 25% or 1 in 4, is constructed like this:
/*`
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
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;
@@ -119,12 +119,12 @@ and a success fraction 0.25, 25% or 1 in 4, is constructed like this:
Which produces the error messages:
[pre
[pre
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;
@@ -137,41 +137,41 @@ and a success fraction 0.25, 25% or 1 in 4, is constructed like this:
/*`
We can, of course, still provide the type explicitly thus:
*/
// Explicit double precision:
negative_binomial_distribution<double> mydist1(8., 0.25);
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);
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);
negative_binomial_distribution<float> mydist4(8.F, 0.25F);
// Explicit float precision, integer arguments promoted to float.
negative_binomial_distribution<float> mydist5(8, 1);
negative_binomial_distribution<float> mydist5(8, 1);
// Explicit double precision:
negative_binomial_distribution<double> mydist6(8., 0.25);
negative_binomial_distribution<double> mydist6(8., 0.25);
// Explicit long double precision:
negative_binomial_distribution<long double> mydist7(8., 0.25);
negative_binomial_distribution<long double> mydist7(8., 0.25);
/*`
And if you have your own RealType called MyFPType,
for example NTL RR (an arbitrary precision type), then we can write:
negative_binomial_distribution<MyFPType> mydist6(8, 1); // Integer arguments -> MyFPType.
[heading 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;
[pre error C2512 no appropriate default constructor available.]
No default constructors are provided for the negative binomial,
@@ -179,13 +179,13 @@ and a success fraction 0.25, 25% or 1 in 4, is constructed like this:
For other distributions, like the normal distribution,
it is obviously very useful to provide 'standard'
defaults for the mean and standard deviation 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.

View File

@@ -1,6 +1,6 @@
// example_error_handling.cpp
// Copyright Paul A. Bristow 2007.
// Copyright Paul A. Bristow 2007, 2010.
// Copyright John Maddock 2007.
// Use, modification and distribution are subject to the
@@ -11,6 +11,11 @@
// Note that this file contains quickbook markup as well as code
// and comments, don't change any of the special comment markups!
// Optional macro definitions described in text below:
// #define BOOST_MATH_DOMAIN_ERROR_POLICY ignore_error
// #define BOOST_MATH_DOMAIN_ERROR_POLICY errno_on_error
// #define BOOST_MATH_DOMAIN_ERROR_POLICY is set to: throw_on_error
//[error_handling_example
/*`
The following example demonstrates the effect of
@@ -59,11 +64,9 @@ We'll begin our sample program with the needed includes:
using std::exception;
/*`
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:
distribution with an invalid degrees of freedom parameter,
the program is set up to handle either an exception or a NaN:
*/
int main()
@@ -77,14 +80,17 @@ int main()
try
{
errno = 0;
students_t dist(degrees_of_freedom); // exception is thrown here if enabled
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:
// Test for error reported by other means:
if((boost::math::isnan)(p))
{
cout << "cdf returned a NaN!" << endl;
cout << "errno is set to: " << errno << 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;
@@ -94,14 +100,13 @@ int main()
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):
(one that *does throw exceptions*):
[pre
Example error handling using Student's t function.
@@ -122,14 +127,13 @@ 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!
errno is set to: 0
]
And finally let's build with:
#define BOOST_MATH_DOMAIN_ERROR_POLICY errno_on_error
Which gives the output:
Which gives the output show errno:
[pre
Example error handling using Student's t function.

View File

@@ -30,6 +30,8 @@
using std::cout;
using std::endl;
// using namespace boost::math::policies; or
using boost::math::policies::policy;
// Possible errors
using boost::math::policies::overflow_error;
@@ -38,7 +40,6 @@ using boost::math::policies::domain_error;
using boost::math::policies::pole_error;
using boost::math::policies::denorm_error;
using boost::math::policies::evaluation_error;
using boost::math::policies::ignore_error;
// Define a custom policy to ignore just overflow:

View File

@@ -6,6 +6,7 @@
#include <iostream>
using std::cout; using std::endl;
#include <cerrno> // for ::errno
//[policy_eg_1

View File

@@ -6,6 +6,7 @@
#include <iostream>
using std::cout; using std::endl;
#include <cerrno> // for ::errno
//[policy_eg_2

View File

@@ -10,6 +10,7 @@
#include <iostream>
using std::cout; using std::endl;
#include <cerrno> // for ::errno
//[policy_eg_4
@@ -17,7 +18,7 @@ using std::cout; using std::endl;
Suppose we want `C::foo()` to behave in a C-compatible way and set
`::errno` on error rather than throwing any exceptions.
We'll begin by including the needed header:
We'll begin by including the needed header for our function:
*/
#include <boost/math/special_functions.hpp>
@@ -25,14 +26,14 @@ We'll begin by including the needed header:
/*`
Open up the "C" namespace that we'll use for our functions, and
define the policy type we want: in this case one that sets
define the policy type we want: in this case a C-style one that sets
::errno and returns a standard value, rather than throwing exceptions.
Any policies we don't specify here will inherit the defaults.
*/
namespace C
{
{ // To hold our C-style policy.
//using namespace boost::math::policies; or explicitly:
using boost::math::policies::policy;

View File

@@ -9,16 +9,17 @@
#include <iostream>
using std::cout; using std::endl;
#include <cerrno> // for ::errno
//[policy_eg_5
#include <boost/math/special_functions.hpp>
//using boost::math::tgamma; // Would create an ambiguity between
// using boost::math::tgamma; // Would create an ambiguity between
// 'double boost::math::tgamma<int>(T)' and
// 'double 'anonymous-namespace'::tgamma<int>(RT)'.
namespace
{ // not named
{ // unnamed
using namespace boost::math::policies;
@@ -26,13 +27,14 @@ typedef policy<
domain_error<errno_on_error>,
pole_error<errno_on_error>,
overflow_error<errno_on_error>,
evaluation_error<errno_on_error>
evaluation_error<errno_on_error>
> c_policy;
BOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(c_policy)
/*`
So that when we call `tgamma(z)`, we really end up calling
`boost::math::tgamma(z, anonymous-namespace::c_policy())`:
So that when we call `tgamma(z)`, we really end up calling
`boost::math::tgamma(z, anonymous-namespace::c_policy())`.
*/
} // close unnamed namespace
@@ -40,11 +42,11 @@ BOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(c_policy)
int main()
{
errno = 0;
cout << "Result of tgamma(30000) is: "
cout << "Result of tgamma(30000) is: "
<< tgamma(30000) << endl;
// tgamma in unnamed namespace in this translation unit (file) only.
cout << "errno = " << errno << endl;
cout << "Result of tgamma(-10) is: "
cout << "Result of tgamma(-10) is: "
<< tgamma(-10) << endl;
cout << "errno = " << errno << endl;
// Default tgamma policy would throw an exception, and abort.

View File

@@ -9,6 +9,7 @@
#include <iostream>
using std::cout; using std::endl;
#include <cerrno> // for ::errno
//[policy_eg_6
@@ -27,9 +28,9 @@ We'll begin by including the needed header for all the distributions:
/*`
Open up an appropriate namespace for our distributions, and
define the policy type we want. Any policies we don't
specify here will inherit the defaults:
Open up an appropriate namespace, calling it `my_distributions`,
for our distributions, and define the policy type we want.
Any policies we don't specify here will inherit the defaults:
*/
@@ -79,22 +80,22 @@ int main()
{
// Construct distribution with something we know will overflow
// (using double rather than if promoted to long double):
my_distributions::normal norm(10, 2);
my_distributions::normal norm(10, 2);
errno = 0;
cout << "Result of quantile(norm, 0) is: "
cout << "Result of quantile(norm, 0) is: "
<< quantile(norm, 0) << endl; // -infinity.
cout << "errno = " << errno << endl;
errno = 0;
cout << "Result of quantile(norm, 1) is: "
cout << "Result of quantile(norm, 1) is: "
<< quantile(norm, 1) << endl; // +infinity.
cout << "errno = " << errno << endl;
// Now try a discrete distribution.
my_distributions::binomial binom(20, 0.25);
cout << "Result of quantile(binom, 0.05) is: "
cout << "Result of quantile(binom, 0.05) is: "
<< quantile(binom, 0.05) << endl; // To check we get integer results.
cout << "Result of quantile(complement(binom, 0.05)) is: "
cout << "Result of quantile(complement(binom, 0.05)) is: "
<< quantile(complement(binom, 0.05)) << endl;
}
@@ -111,7 +112,7 @@ Result of quantile(binom, 0.05) is: 1
Result of quantile(complement(binom, 0.05)) is: 8
]
This mechanism is particularly useful when we want to define a
This mechanism is particularly useful when we want to define a
project-wide policy, and don't want to modify the Boost source
or set project wide build macros (possibly fragile and easy to forget).

View File

@@ -9,6 +9,7 @@
#include <iostream>
using std::cout; using std::endl;
#include <cerrno> // for ::errno
//[policy_eg_7

View File

@@ -45,7 +45,8 @@ boost/math/policies/error_handling.hpp like this:
So out first job is to include the header we want to use, and then
provide definitions for our user-defined error handlers that we want to use.
We only provide our special domain and pole error handlers, other errors use the default.
We only provide our special domain and pole error handlers;
other errors like overflow and underflow use the default.
*/
#include <boost/math/special_functions.hpp>

View File

@@ -22,8 +22,8 @@ Each error handler has the general form:
template <class T>
T user_``['error_type]``(
const char* function,
const char* message,
const char* function,
const char* message,
const T& val);
and accepts three arguments:
@@ -32,7 +32,7 @@ and accepts three arguments:
[[const char* function]
[The name of the function that raised the error, this string
contains one or more %1% format specifiers that should be
replaced by the name of type T.]]
replaced by the name of real type T, like float or double.]]
[[const char* message]
[A message associated with the error, normally this
contains a %1% format specifier that should be replaced with
@@ -53,7 +53,7 @@ As before we'll include the headers we need first:
#include <boost/math/special_functions.hpp>
/*`
Next we'll implement our own error handlers for each type of error,
Next we'll implement our own error handlers for each type of error,
starting with domain errors:
*/
@@ -85,7 +85,7 @@ T user_domain_error(const char* function, const char* message, const T& val)
// int prec = std::numeric_limits<T>::max_digits10; // For C++0X Standard Library
msg += (boost::format(message) % boost::io::group(std::setprecision(prec), val)).str();
/*`
Now we just have to do something with the message, we could throw an
Now we just have to do something with the message, we could throw an
exception, but for the purposes of this example we'll just dump the message
to std::cerr:
*/
@@ -97,7 +97,7 @@ T user_domain_error(const char* function, const char* message, const T& val)
}
/*`
Pole errors are essentially a special case of domain errors,
Pole errors are essentially a special case of domain errors,
so in this example we'll just return the result of a domain error:
*/
@@ -126,9 +126,9 @@ T user_overflow_error(const char* function, const char* message, const T& val)
msg += message;
std::cerr << msg << std::endl;
// Value passed to the function is an infinity, just return it:
return val;
return val;
}
/*`
@@ -150,9 +150,9 @@ T user_underflow_error(const char* function, const char* message, const T& val)
msg += message;
std::cerr << msg << std::endl;
// Value passed to the function is zero, just return it:
return val;
return val;
}
/*`
@@ -174,13 +174,13 @@ T user_denorm_error(const char* function, const char* message, const T& val)
msg += message;
std::cerr << msg << std::endl;
// Value passed to the function is denormalised, just return it:
return val;
return val;
}
/*`
Which leaves us with evaluation errors, these occur when an internal
Which leaves us with evaluation errors: these occur when an internal
error occurs that prevents the function being fully evaluated.
The parameter /val/ contains the closest approximation to the result
found so far:
@@ -205,9 +205,8 @@ T user_evaluation_error(const char* function, const char* message, const T& val)
std::cerr << msg << std::endl;
// What do we return here? This is generally a fatal error,
// that should never occur, just return a NaN for the purposes
// of the example:
// What do we return here? This is generally a fatal error, that should never occur,
// so we just return a NaN for the purposes of the example:
return std::numeric_limits<T>::quiet_NaN();
}

View File

@@ -42,8 +42,8 @@ BOOST_MATH_DECLARE_DISTRIBUTIONS(double, my_policy)
// myspace::mypolicy:
//
// This compiles but throws a domain error exception at runtime.
// (Caution, if you omit the try'n'catch blocks, it will just terminate,
// giving no clues as to why!
// Caution! If you omit the try'n'catch blocks,
// it will just silently terminate, giving no clues as to why!
// So try'n'catch blocks are very strongly recommended.
void test_cauchy()