Standard Deviation definition states:
A quantity expressing by how much the members of a group differ from the mean value for the group.
The logic below calculates the Standard Deviation for the population of values. If the data is being considered a population on its own, we divide by the number of data points, say N. If the data is a sample from a larger population, we divide by one fewer than the number of data points in the sample, n-1. So you can change the formula accordingly.
Ruby code sample:
#sample = Array[1,2,3,4,5,6,7,8]
sample = Array[1,2,3,4,5]
def calc_standard_deviation(values)
avg = values.sum {|x| x.to_f} / values.size.to_f
Math.sqrt(values.sum {|x| (x.to_f - avg.to_f) ** 2} / values.size)
end
puts "Standard Deviation is: " + calc_standard_deviation(sample).to_s
Run the Ruby code to test as below in VS Code:
PS C:\code\Ruby test> ruby .\stdDev.rb
#Ruby Output: Standard Deviation is: 1.4142135623730951
C# code sample:
static void Main(string[] args)
{
//double[] sample = new double[8] { 1, 2, 3, 4, 5, 6, 7, 8 };
double[] sample = new double[5] { 1, 2, 3, 4, 5 };
Console.WriteLine("Standard Deviation is: " + StdDev(sample));
}
public static double StdDev(IEnumerable<double> values)
{
// Get the mean.
double mean = values.Sum() / values.Count();
// Get the sum of the squares of the differences
// between the values and the mean.
var squares_query =
from double value in values
select (value - mean) * (value - mean);
double sum_of_squares = squares_query.Sum();
return Math.Sqrt(sum_of_squares / values.Count());
}
C# Output: Standard Deviation is: 1.4142135623731