ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

Standard Deviation LINQ extension method

Typical standard deviation formula set in LINQ fluent syntax. For when Average, Min, and Max just aren't enough information.

Source

public static double StdDevP(this IEnumerable<int> source)
{
    return StdDevLogic(source, 0);
}

public static double StdDev(this IEnumerable<int> source)
{
    return StdDevLogic(source, 1);
}

private static double StdDevLogic(this IEnumerable<int> source, int buffer = 1)
{
    if (source == null)
    { throw new ArgumentNullException("source"); }

    var data = source.ToList();
    var average = data.Average();
    var differences = data.Select(u => Math.Pow(average - u, 2.0)).ToList();
    return Math.Sqrt(differences.Sum() / (differences.Count() - buffer));
}

Example

var nums = new[] { 11, 12, 13, 12, 13, 15, 12, 14, 15, 15, 12, 14, 15 };
//Prints out the standard deviation of the entire data set (population)
nums.StdDevP();
//Prints out the standard deviation of the entire data set, but makes allowances for missing data points.
nums.Take(10).StdDev();

Author: ParrottSquawk

Submitted on: 6 aug 2013

Language: C#

Type: System.Double

Views: 8092