Skip to main content

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

// ----------------------------------------------------------------------------
// 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.
// ----------------------------------------------------------------------------

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 Usage:
// ----------------------------------------------------------------------------

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();