Standard Deviation Calculation in .NET To Simulate Excel STDEVPA

By Robbe D. Morris

Printer Friendly Version

Robbe Morris
Robbe & Melisa Morris
Here's a quick code sample that demonstrates how to calculate standard deviation for an array of values in .NET ( C# / VB.NET ).  This method duplicates the same standard deviation ( STDEVPA ) function that exists in Excel.


Sample Code
using System;

namespace ConsoleApplication2
{

   class Class1
   {
 
     [STAThread]
     static void Main(string[] args)
     {
     
       double[] test1 = new double[7];
       double[] test2 = new double[8];
            
       try
       {

          test1[0] = 9;
          test1[1] = 9;
          test1[2] = 9;
          test1[3] = 9;
          test1[4] = 9;
          test1[5] = 9;
          test1[6] = 9;

          test2[0] = 3.3;
          test2[1] = 5.6;
          test2[2] = 7.2;
          test2[3] = 5.6;
          test2[4] = 9;
          test2[5] = 2.1;
          test2[6] = 8.8;
          test2[7] = 2.1;

          // test #1 should return zero because there is
          // no variance between any of the data points.

          Console.WriteLine(StandardDeviation(test1).ToString());

          Console.WriteLine(StandardDeviation(test2).ToString());	

       }
       catch (Exception e) 
       {
          Console.WriteLine(e.Message);
       }
       finally
       {
          Console.ReadLine();
       }
  }

  private static double StandardDeviation(double[] data)
  {

    double ret = 0;
    double DataAverage = 0;
    double TotalVariance = 0;
    int Max = 0;
 
    try
    {

      Max = data.Length;
				
      if (Max == 0) { return ret; }

      DataAverage = Average(data);

      for(int i=0;i<Max;i++)
      {
        TotalVariance += Math.Pow(data[i] - DataAverage,2); 
      }

      ret = Math.Sqrt(SafeDivide(TotalVariance,Max));

    }
    catch (Exception) { throw; }
    return ret;
 }

 private static double Average(double[] data)
  {

    double ret = 0;
    double DataTotal = 0;
 
    try
    {
 
      for(int i=0;i<data.Length;i++)
      {
        DataTotal += data[i]; 
      }

      return SafeDivide(DataTotal,data.Length);

    }
    catch (Exception) { throw; }
    return ret;
 }

  private static double SafeDivide(double value1,double value2)
  {

    double ret = 0;

    try
    {

      if ((value1 == 0) || ( value2 == 0)) { return ret; }

      ret =  value1 / value2;
    
    }
    catch { } 
    return ret;
  }


  }
}


Robbe has been a Microsoft MVP in C# since 2004.  He is also the co-founder of NullSkull.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice.