/// ------------------------------------------------------ /// SwarmOps - Numeric and heuristic optimization for C# /// Copyright (C) 2003-2011 Magnus Erik Hvass Pedersen. /// Please see the file license.txt for license details. /// SwarmOps on the internet: http://www.Hvass-Labs.org/ /// ------------------------------------------------------ using System.Collections.Generic; using System.Linq; namespace SwarmOps.Extensions { /// /// Various extensions to System-classes. /// public static partial class ExtensionMethods { /// /// Computes the sum of squares of a sequence of System.Double values that /// are obtained by invoking a transform function on each element of the /// input sequence. /// /// The type of the elements of source. /// A sequence of values to calculate the sum of squares of. /// A transform function to apply to each element. /// The sum of squares of the sequence of values. public static double SumSquares(this IEnumerable source, System.Func selector) { return source.Sum((elm) => { double x = selector(elm); return x * x; }); } /// /// Computes the standard deviation of a sequence of System.Double values that /// are obtained by invoking a transform function on each element of the /// input sequence. /// /// The type of the elements of source. /// A sequence of values to calculate the standard deviation of. /// A transform function to apply to each element. /// The standard deviation of the sequence of values. public static double StdDev(this IEnumerable source, System.Func selector) { double sumSquares = source.SumSquares(selector); double mean = source.Average(selector); double stdDev = System.Math.Sqrt(sumSquares / source.Count() - mean * mean); return stdDev; } } }