public static double StandardDeviation(IEnumerable‹double› sequence)
{
var computation = ComputeSumAndSumOfSquares(sequence);
var variance = computation.SumOfSquares - computation.Sum * computation.Sum / computation.Count;
return Math.Sqrt(variance / computation.Count);
}
private static (int Count, double Sum, double SumOfSquares) ComputeSumAndSumOfSquares(IEnumerable‹double› sequence)
{
double sum = 0;
double sumOfSquares = 0;
int count = 0;
foreach (var item in sequence)
{
count++;
sum += item;
sumOfSquares += item * item;
}
return (count, sum, sumOfSquares);
}