Implementing Excel’s STDDEVP in C#

I have been adding functionality to one of my applications. Without going into huge amounts of detail, it’s a C# application that pushes data out to Microsoft Excel – end users like Excel! The functionality that I’m adding was prototyped inside Microsoft Excel using simulated data and…the Excel Analysis Toolpak. To cut a long story short, I really wanted to remove the reliance on the Toolpak. In fact, I really wanted as much of the control element pulled back into the C# application, i.e. I wanted Excel doing more presentation of data and less scripting.

Part of that functionality involved replicating a few of Excel’s statistical functions, most notably STDDEVP (more details here)

Of course, it’s very likely that there’s a .NET implementation available in the .NET Framework…however my brief search was inconclusive, so I set about writing my own. The code you see below will compile and run using Visual Studio 2005. If you are using Visual Studio 2008 you can take advantage of the built in Sum, Average and Count methods (e.g. total = n.Sum(); instead of the foreach…total+=num loop)

[C#, compiled and tested using Visual Studio 2005]

class Program
{
    static public double STDDEVP(params double[] n)
    {
        double total = 0, average = 0;

        foreach (double num in n)
        {
            total += num;     
        }
  
        average = total / n.Length;
        
        double runningTotal = 0;

        foreach (double num in n)
        {
            runningTotal += ((num - average) * (num - average));
        }

        double calc = runningTotal / n.Length;
        double standardDeviationP = Math.Sqrt(calc);

        return standardDeviationP;
    }

    static void Main(string[] args)
    {
        double s = STDDEVP(1, 2, 3, 4, 5, 6, 7);
        Console.WriteLine(s);
        Console.ReadLine();
    }
}

This worked for me – your mileage may vary.

Technorati Tags: , , ,