Posted by: hakutheblack March 6, 2009
Normal Distribution (Bell Curve) in C#
Login in to Rate this Post:     0       ?        
NORMDIST is a statistical function. It has a "nice" formula that is given in the Excel help (go to index, write NORMDIST). C# supports all these functions, just be careful to use the largest possible data types in C# (long, double) otherwise you will lose accuracy.

You can see the help topic with the formula also here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/office97/html/sec02.asp

More info:
http://support.microsoft.com/default.aspx?kbid=827371&product=xl2003

What normal distribution is:
http://pirate.shu.edu/~wachsmut/Teaching/MATH1101/Testing/distribution.html

 

SIMPLE C# Implementation

 /// <summary>
    /// Normal Distribution
    /// </summary>
    /// <param name="x">The value for which you want the distribution.</param>
    /// <param name="mean">The arithmetic mean of the distribution.</param>
    /// <param name="deviation">The standard deviation of the distribution.</param>
    /// <param name="cumulative">If cumulative is true, functions returns the cumulative distribution, otherwise the function returns the probability mass.</param>
    /// <returns>Returns the normal distribution for the specified mean and standard deviation.</returns>
    public static double NormalDistribution(double x, double mean, double deviation, bool cumulative)
    {
      if(cumulative)
        return CumulativeDistribution(x, mean, deviation);
      else
        return NormalDensity(x, mean, deviation);
    }

    private static double NormalDensity(double x, double mean, double deviation)
    {
      return Math.Exp(-(Math.Pow((x - mean)/deviation, 2)/2))/Math.Sqrt(2*Math.PI)/deviation;
    }

    private static double CumulativeDistribution(double x, double mean, double deviation)
    {
      // TODO: Change the number of iterations (16) for more or less precision.
      // You could also change the logic of the recursive function (stop calling
      // for more terms, when the values are below a specific threshold for example.
      return (ErrorFunction((x - mean)/deviation/Math.Sqrt(2), 0, 16) + 1)/2;
    }

    private static double ErrorFunction(double x, int iteration, int iterations)
    {
      double partValue;
      partValue = 2/Math.Sqrt(Math.PI)*Math.Pow(-1, iteration)*Math.Pow(x, 2*iteration + 1)/Factorial(iteration)/(2*iteration + 1);
     
      if(iteration==iterations)
        return partValue;
      else
        return ErrorFunction(x, iteration + 1, iterations) + partValue;
    }

    private static int Factorial(int x)
    {
      if(x==0)
        return 1;
      else
        return x*Factorial(x-1);
    }
Read Full Discussion Thread for this article