namespace MyApp.Extensions { using System; using System.Collections.Generic; using System.Linq; public static class MathExtensions { /// Calculates the Standard Deviation for the collection of integers. /// The collection. /// A double. public static double StandardDeviation(this IEnumerable collection) { return CalculateStandardDeviation(collection); } /// Calculates the Standard Deviation for the collection of double. /// The collection. /// A double. public static double StandardDeviation(this IEnumerable collection) { return CalculateStandardDeviation(collection); } /// Calculates the Standard Deviation for the collection of floats. /// The collection. /// A float. public static float StandardDeviation(this IEnumerable collection) { return CalculateStandardDeviation(collection); } /// Calculates the Standard DeviationP for the collection of integers. /// The collection. /// A double. public static double StandardDeviationP(this IEnumerable collection) { return CalculateStandardDeviation(collection); } /// Calculates the Standard DeviationP for the collection of doubles. /// The collection. /// A double. public static double StandardDeviationP(this IEnumerable collection) { return CalculateStandardDeviation(collection, 0); } /// Calculates the Standard Deviation for the collection of floats. /// The collection. /// A double. public static double StandardDeviationP(this IEnumerable collection) { return CalculateStandardDeviation(collection, 0); } /// Calculates the Standard Deviation for the collection of doubles. /// Thrown when one or more required arguments are null. /// The collection. /// Buffer size(Optional) /// The calculated standard deviation. /// /// ### Indicates a null collection. private static double CalculateStandardDeviation(this IEnumerable collection, int buffer = 1) { if (collection == null) throw new ArgumentNullException("collection"); var data = collection.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)); } /// Standards the deviation p. /// The collection. /// The calculated standard deviation. private static double CalculateStandardDeviation(this IEnumerable collection) { return CalculateStandardDeviation(collection.Select(x => (double)x)); } /// Standards the deviation p. /// Thrown when one or more required arguments are null. /// The collection. /// Buffer size(Optional) /// The calculated standard deviation. /// /// ### Indicates a null collection. private static float CalculateStandardDeviation(this IEnumerable collection, int buffer = 1) { if (collection == null) throw new ArgumentNullException("collection"); var data = collection.ToList(); var average = data.Average(); var differences = data.Select(u => Math.Pow(average - u, 2.0)).ToList(); return (float)Math.Sqrt(differences.Sum() / (differences.Count() - buffer)); } } }