Search code examples
c#excelnormal-distribution

c# NormalDistribution implementation


I need the C# implementation(source code) of a NormalDistribution function in System.Web.DataVisualization.dll, I tried source using the already available functions from github to calculate NORM.S.DIST but they are not accurate and not matching with excel values.

Below is the code I used and it gives me 1.2664557440189636E-43 (almost zero) for an input of 13.803404798240017. On the other hand excel and the NormalDistribution function in DataVisualization retruns 1 as the result.

public static double NS(double zValue)
{
    const double b1 = 0.319381530;
    const double b2 = -0.356563782;
    const double b3 = 1.781477937;
    const double b4 = -1.821255978;
    const double b5 = 1.330274429;
    const double p = 0.2316419;
    const double c = 0.39894228;

    if (zValue >= 0.0)
    {
        double t = 1.0 / (1.0 + p * zValue);
        return (1.0 - c * Math.Exp(-zValue * zValue / 2.0) * t * (t * (t * (t * (t * b5 + b4) + b3) + b2) + b1));
     }
     else
     {
         double t = 1.0 / (1.0 - p * zValue);
         return (c * Math.Exp(-zValue * zValue / 2.0) * t * (t * (t * (t * (t * b5 + b4) + b3) + b2) + b1));
      }
}

I tried ILSpy to see the code in DataVisualization.dll but no luck, please suggest how to we get that source code(if possible), I thought MS has open sourced their .Net code base but it's not true for all assemblies. or is there any better way to calculate NORM.S.DIST with good accuracy?

Thanks!!


Solution

  • The difference you mention between the two calculations could be due to the difference between the density distribution and cumulative distribution. For a z value of 13.80, the density function would be virtually 0 while the cumulative distribution would be virtually 1. The excel function NORMAL.S.DISTR(z,cumulative) allows to specify this difference as an argument. I would suggest looking at both implementations to make sure they are both either cumulative or density. Regarding alternative libraries I would recommend the NuGet package: "MathNet.Numerics" This package contains implementations of several statistical distributions.