82 lines
2.9 KiB
C#
82 lines
2.9 KiB
C#
using System;
|
|
|
|
namespace bts.analytics
|
|
{
|
|
public static class Probability
|
|
{
|
|
public static double dN(double z)
|
|
{
|
|
const double INVSQRT2PI = 0.39894228040143267793994605993438;
|
|
return Math.Exp(-0.5 * z * z) * INVSQRT2PI;
|
|
}
|
|
|
|
public static double normal_pdf(double z)
|
|
{
|
|
const double MAXSTD = 37.61588707;
|
|
const double mindN = 2.2250738585134157e-308;
|
|
if (Math.Abs(z) > MAXSTD) return mindN;
|
|
else return dN(z);
|
|
}
|
|
|
|
public static double inverse_normal(double x, int guess, double zguess)
|
|
{
|
|
if (x > 1.0 || x < 0.0) return 0.0;
|
|
double z;
|
|
const double err_tol = 1.0e-15;
|
|
if (guess == 0) z = (x > 0.5) ? 0.67 : -0.67;
|
|
else z = zguess;
|
|
double Nz = normal_cdf(z);
|
|
int counter = 0;
|
|
for (; Math.Abs(Nz - x) > err_tol && counter < 20; counter++)
|
|
{
|
|
double epsilon = z * (x - Nz) / dN(z);
|
|
z += epsilon * (1.0 + epsilon * (0.5 + epsilon * 5.0 / 16.0)) / z;
|
|
Nz = normal_cdf(z);
|
|
}
|
|
if (double.IsNaN(z) && guess != 0) return inverse_normal(x, 0, 0.0);
|
|
else return z;
|
|
}
|
|
|
|
private readonly static double MAXSTD = 37.5193793471444;
|
|
private readonly static double MinNormCDF = 2.2250738585152E-308;
|
|
public static double normal_cdf(double x)
|
|
{
|
|
double XAbs = Math.Abs(x);
|
|
double Cumnorm = MinNormCDF;
|
|
if (XAbs < MAXSTD)
|
|
{
|
|
double Exponential = Math.Exp(-0.5 * XAbs * XAbs);
|
|
if (XAbs < 7.07106781186547)
|
|
{
|
|
double build = 3.52624965998911E-02 * XAbs + 0.700383064443688;
|
|
build = build * XAbs + 6.37396220353165;
|
|
build = build * XAbs + 33.912866078383;
|
|
build = build * XAbs + 112.079291497871;
|
|
build = build * XAbs + 221.213596169931;
|
|
build = build * XAbs + 220.206867912376;
|
|
Cumnorm = Exponential * build;
|
|
build = 8.83883476483184E-02 * XAbs + 1.75566716318264;
|
|
build = build * XAbs + 16.064177579207;
|
|
build = build * XAbs + 86.7807322029461;
|
|
build = build * XAbs + 296.564248779674;
|
|
build = build * XAbs + 637.333633378831;
|
|
build = build * XAbs + 793.826512519948;
|
|
build = build * XAbs + 440.413735824752;
|
|
Cumnorm = Cumnorm / build;
|
|
}
|
|
else
|
|
{
|
|
double build = XAbs + 0.65;
|
|
build = XAbs + 4.0 / build;
|
|
build = XAbs + 3.0 / build;
|
|
build = XAbs + 2.0 / build;
|
|
build = XAbs + 1.0 / build;
|
|
Cumnorm = Exponential / (build * 2.506628274631);
|
|
}
|
|
}
|
|
if (x > 0) Cumnorm = 1.0 - Cumnorm;
|
|
return Cumnorm;
|
|
}
|
|
}
|
|
}
|