#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
namespace c
{
const double pi = 3.14159265358979323846;
const double rad2pi = std::sqrt(2*pi);
const int numIterations =100;
}
double getPercentage(int val, int mean, int stddev)
{
double dif = (val - mean) / (double)(stddev);
return std::exp(-0.5*dif*dif) / (c::rad2pi * stddev);
}
// tition
double getNormalDistributionPhi(double x)
{ //reference: http://e...content-available-to-author-only...a.org/wiki/Normal_distribution#Cumulative_distribution_function
//code copied from pascal from Wikipedia and translated to c++. I have not made any checks for errors.
//Please give the code a second look.
//Original pascal code from wikipedia:
//begin
// sum:=x;
// value:=x;
// for i:=1 to 100 do
// begin
// value:=(value*x*x/(2*i+1));
// sum:=sum+value;
// end;
// result:=0.5+(sum/sqrt(2*pi))*exp(-(x*x)/2);
//end;
double value=x;
double sum=x;
for (int i=1; i<c::numIterations; i++)
{ value*=x*x/(2*i+1);
sum+=value;
}
return 0.5+(sum/std::sqrt(2*c::pi))*std::exp(-(x*x)/2);
}
double getPercentageNormalDistribution(double val, double mean, double stddev) //all arguments should be floating point, int is no good!
{ return getNormalDistributionPhi((val-mean)/stddev);
}
double getPercentageAlt2(int val, int mean, int stddev)
{
return getPercentageNormalDistribution( ((double) val) + 0.5, mean, stddev ) -
getPercentageNormalDistribution( ((double) val) - 0.5, mean, stddev );
}
// JL Borges
double phi( double x, double mu, double sigma )
{ return 0.5 + 0.5 * ( std::erf( (x-mu) / ( std::sqrt(2.0) * sigma ) ) ) ; }
double getPercentageAlt(int val, int mean, int stddev)
{
return phi( ((double) val) + 0.5, mean, stddev ) - phi( ((double) val) - 0.5, mean, stddev );
}
int main()
{
int mean = 20;
int stddev = 2;
int drawcount = 40;
cout << "mean : " << mean << "\n";
cout << "stddev : " << stddev << "\n\n";
for(int i = 0; i < drawcount; ++i)
{
cout << setw(2) << i << " -> " << fixed << getPercentage(i,mean,stddev) << '\t' // ne555
<< fixed << getPercentageAlt(i,mean,stddev) << '\t' // JLBorges
<< fixed << getPercentageAlt2(i,mean,st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