Fetches the standard deviation of a set given a function defining the value from an object to use. - CSharp System

CSharp examples for System:Object

Description

Fetches the standard deviation of a set given a function defining the value from an object to use.

Demo Code

// Licensed under the Apache License, Version 2.0 (the "License");
using System.Linq;
using System.Collections.Generic;
using System;/*from w  ww . j  av a  2s  .com*/

public class Main{
        /// <summary>
        /// Fetches the standard deviation of a set given a function defining the value from an object to use.
        /// </summary>
        public static float StdDev<T>(this ICollection<T> items, Func<T, int> value, float mean) {
            return StdDev(items, t => (float) value(t), mean);
        }
        /// <summary>
        /// Fetches the standard deviation of a set given a function defining the value from an object to use.
        /// </summary>
        public static float StdDev<T>(this ICollection<T> items, Func<T, float> value, float mean) {
            float standardDeviation = 0;
            float count = items.Count();

            if (count > 1) {
                float sum = items.Select(value).Sum(s => (s - mean) * (s - mean));

                standardDeviation = (float)Math.Sqrt(sum / count);
            }

            return standardDeviation;
        }
}

Related Tutorials