Created
May 14, 2012 11:44
-
-
Save sinairv/2693528 to your computer and use it in GitHub Desktop.
Mean, Variance, and Standard Deviation Methods
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment