BLOG.CSHARPHELPER.COM: Make an extension method that calculates standard deviation in C#
Make an extension method that calculates standard deviation in C#
This example simply uses the following extension method to calculate standard deviation.
public static class StatsStuff { // Return the standard deviation of an array of Doubles. // // If the second argument is True, evaluate as a sample. // If the second argument is False, evaluate as a population. public static double StdDev(this IEnumerable<int> values, bool as_sample) { // Get the mean. double mean = values.Sum() / values.Count();
// Get the sum of the squares of the differences between // the values and the mean. var squares_query = (from int value in values select (value - mean) * (value - mean)); double sum_of_squares = squares_query.Sum();
The calculation is straightforward.
The sample standard deviation is given by .
The population standard deviation is given by .
The oddest thing about this example is the fact that one extension method cannot calculate standard deviation for more than one data type. This version assumes the values are in an IEnumerable containing integers but the exact same calculation works for floats, doubles, and other numeric data types. You could try to make this a generic extension method but unfortunately you cannot specify that the parameter data type must be numeric. You might be able to use an IEnumerable of objects and convert the objects into doubles, but that seems inelegant and inefficient. If you figure out how to do this properly without making a separate extension method for each data type, please let me know. (If you look at the documentation, it seems that predefined extension methods such as Average that perform calculations on numeric types have multiple versions for different data types.)
Using the extension method is easy. The following code shows how the main program uses it to display the standard deviations for the list of integers named values.
Comments