vote buttons
2
07 Feb 2015 by K Bonneau

Variance and Standard Deviation

Standard Deviation is a measure which indicates how spread out a distribution is. It is equal to the square root of the variance. Variance is the average of the squared differences of the numbers from the mean.
Contract
IMathUtilities
double Variance(IEnumerable<double> values); double StandardDeviation(IEnumerable<double> values);
Test Cases
vote buttons
1
Created By K Bonneau
public void GivenFiniteNumbers_VarianceReturnsCorrectValue(IMathUtilities mathUtilities) { double actual = mathUtilities.Variance(new double[] {10,10,30,55,60,66,70,83}); double expected = 679.75; Assert.AreEqual(expected, actual); }
vote buttons
1
Created By K Bonneau
public void GivenFiniteNumbers_StandardDeviationReturnsCorrectValue(IMathUtilities mathUtilities) { double actual = mathUtilities.StandardDeviation(new double[] {10,10,30,55,60,66,70,83}); double expected = 26.072; double tolerance = .01; Assert.AreEqual(expected, actual, tolerance); }
vote buttons
0
Created By K Bonneau
public void GivenEmptyList_VarianceReturnsZero(IMathUtilities mathUtilities) { double actual = mathUtilities.Variance(new double[] {}); double expected = 0; Assert.AreEqual(expected, actual); }
vote buttons
0
Created By K Bonneau
public void GivenEmptyList_StandardDeviationReturnsZero(IMathUtilities mathUtilities) { double actual = mathUtilities.StandardDeviation(new double[] {}); double expected = 0; Assert.AreEqual(expected, actual); }
You must be logged in to add test cases

1 Solution

vote buttons
1
0.04
avg time in ms
07 Feb 2015 by K Bonneau
public class MathUtilities : IMathUtilities { public double Variance(IEnumerable<double> values) { if (values == null || values.Count() == 0) return 0; double meanValue = values.Average(); double sum = 0; foreach (double value in values) sum += Math.Pow(value - meanValue, 2); return sum / (double)values.Count(); } public double StandardDeviation(IEnumerable<double> values) { return Math.Sqrt(Variance(values)); } }
Test Case Run Summary
GivenFiniteNumbers_VarianceReturnsCorrectValue
GivenFiniteNumbers_StandardDeviationReturnsCorrectValue
GivenEmptyList_VarianceReturnsZero
GivenEmptyList_StandardDeviationReturnsZero
download solution
Try this Solution
Comments