File size: 2,417 Bytes
b1b3bae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/// ------------------------------------------------------
/// 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
{
    /// <summary>
    /// Various extensions to System-classes.
    /// </summary>
    public static partial class ExtensionMethods
    {
        /// <summary>
        /// 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.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements of source.</typeparam>
        /// <param name="source">A sequence of values to calculate the sum of squares of.</param>
        /// <param name="selector">A transform function to apply to each element.</param>
        /// <returns>The sum of squares of the sequence of values.</returns>
        public static double SumSquares<TSource>(this IEnumerable<TSource> source, System.Func<TSource, double> selector)
        {
            return source.Sum((elm) => { double x = selector(elm); return x * x; });
        }

        /// <summary>
        /// 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.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements of source.</typeparam>
        /// <param name="source">A sequence of values to calculate the standard deviation of.</param>
        /// <param name="selector">A transform function to apply to each element.</param>
        /// <returns>The standard deviation of the sequence of values.</returns>
        public static double StdDev<TSource>(this IEnumerable<TSource> source, System.Func<TSource, double> selector)
        {
            double sumSquares = source.SumSquares(selector);
            double mean = source.Average(selector);

            double stdDev = System.Math.Sqrt(sumSquares / source.Count() - mean * mean);

            return stdDev;
        }
    }
}