1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <cmath>
using namespace std;
int nu; // degrees of freedom
double cnu; // main coefficient in t distribution
//======================================================================
// Function prototypes
void setCoefficients();
double pdf( double x );
double trapezium( double a, double b, int n, double f( double ) );
//======================================================================
int main()
{
const int n = 1000; // number of intervals for integration; increase if necessary
double a, b;
cout << "Input lower limit, a: " ; cin >> a;
cout << "Input upper limit, b: " ; cin >> b;
cout << "Input degrees of freedom, nu: "; cin >> nu;
setCoefficients();
cout << "\nProbability: " << trapezium( a, b, n, pdf ) << '\n';
}
//======================================================================
void setCoefficients()
{
double pi = 4.0 * atan( 1.0 );
cnu = tgamma( 0.5 * ( nu + 1.0 ) ) / tgamma( 0.5 * nu ) / sqrt( nu * pi );
}
//======================================================================
double pdf( double x ) // pdf of the student's t distribution
{
return cnu * pow( 1.0 + x * x / nu, -0.5 * ( nu + 1.0 ) );
}
//======================================================================
double trapezium( double a, double b, int n, double f( double ) ) // numerical integration of f(x) from a to b
{
double dx = ( b - a ) / n;
double integral = f( a ) + f(b);
for ( int i = 1; i <= n - 1; i++ ) integral += 2.0 * f( a + i * dx );
integral *= dx / 2.0;
return integral;
}
//======================================================================
|