Standard Deviation of IEnumerable<TValue> - CSharp System

CSharp examples for System:Math Statistics

Description

Standard Deviation of IEnumerable<TValue>

Demo Code

// This project is licensed under the BSD license.  See the License.txt file for more information.
using System.Globalization;
using System.Collections.Generic;
using System;/*w  w w. j av a  2 s . c  o m*/

public class Main{
        public static double StandardDeviation<TValue>(this IEnumerable<TValue> values, out double mean)
        {
            var converted = new List<double>();
            foreach(TValue value in values)
            {
                converted.Add(Convert.ToDouble(value, CultureInfo.InvariantCulture));
            }
            return StandardDeviation(converted, out mean);
        }
        public static double StandardDeviation(this IEnumerable<double> values, out double mean)
        {
            mean = values.Mean();
            double sumOfDiffSquares = 0;
            int count = 0;

            foreach(double d in values)
            {
                double diff = (d - mean);
                sumOfDiffSquares += diff * diff;
                count++;
            }

            return Math.Sqrt(sumOfDiffSquares / count);
        }
        public static double Mean(this IEnumerable<double> values)
        {
            double sum = 0;
            int count = 0;

            foreach(double d in values)
            {
                sum += d;
                count++;
            }

            return sum / count;
        }
}

Related Tutorials