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
|
#include <iostream>
#include <cmath>
using namespace std;
// Returns the probability of x, given the distribution described by mu and sigma.
double pdf(double x, double mu, double sigma)
{
static const double pi = 3.14159265;
return exp( -1 * (x - mu) * (x - mu) / (2 * sigma * sigma)) / (sigma * sqrt(2 * pi));
}
// Returns the integral from -inf to x of any function that accepts x and 2 other parameters
double cdf(double x, double arg1, double arg2, double(*pPDF)(double,double,double))
{
double sum = 0;
double ninf = -1e3; // Negative infinity, just use something small
double n = 1e7; // The number of "buckets" that we'll calculate, more is more accurate but takes more time;
for (double k = 1.; k < n-1; k++)
sum += pPDF( x + k*(x-ninf)/n ,arg1,arg2);
return ((x - ninf) / n) * ((pPDF(x,arg1,arg2) + pPDF(ninf,arg1,arg2))/2 + sum);
}
int main()
{
double x, mu, sigma;
cout << "x, mu, sigma: ";
cin >> x >> mu >> sigma;
cout << "PDF of x is: " << pdf(x,mu,sigma) << endl;
cout << "CDF of x is: " << cdf(x,mu,sigma,pdf) << endl; // Note we added a pointer to your pdf function
return 0;
}
|