Code Snippet for Calculating Mean, Variance, and Standard Deviation
Here are the methods to calculate mean, variance, and standard deviation of a vector of values. These are put here for easy reference, so that I do not need to rewrite them again (and again (and again)).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Calculates the mean of an array of values | |
/// </summary> | |
/// <param name="v">the array of values to calculate their mean</param> | |
/// <returns>The mean of the array of values</returns> | |
public static double Mean(double[] v) | |
{ | |
double sum = 0.0; | |
for (int i = 0; i < v.Length; i++) | |
{ | |
sum += v[i]; | |
} | |
return sum / v.Length; | |
} | |
/// <summary> | |
/// Calculates the variance of an array of values | |
/// </summary> | |
/// <param name="v">the array of values to calculate their variance</param> | |
/// <returns>The variance of the array of values</returns> | |
public static double Variance(double[] v) | |
{ | |
double mean = Mean(v); | |
double sum = 0.0; | |
for (int i = 0; i < v.Length; i++) | |
{ | |
sum += (v[i] - mean) * (v[i] - mean); | |
} | |
int denom = v.Length - 1; | |
if (v.Length <= 1) | |
denom = v.Length; | |
return sum / denom; | |
} | |
/// <summary> | |
/// Calculates the standard deviation of an array of values | |
/// </summary> | |
/// <param name="v">the array of values to calculate their standard deviation</param> | |
/// <returns>The standard deviation of the array of values</returns> | |
public static double StDev(double[] v) | |
{ | |
return Math.Sqrt(Variance(v)); | |
} |