LINQ - Calculate average and standard deviation in one go
I have a list with values:
List<double> values = new List<double> {4,5,7,7,8,98,1,3,4,2,2,4,5,5,6,7,8,5,3,2,9,4,5,6,7,8};
I want to get:
the average = sum(values)/n
standard deviation = sqrt( (sum(values^2) - n*average)/(n-1) ) as quickly as possible (I need to do this for many many lists)
Is it possible to let the computer iterate only once over this list to get:
- the sum of the values
- the sum of the values squared?
Re: LINQ - Calculate average and standard deviation in one go
There's no need for LINQ I see. I converted it into this:
Code:
mean = 0;
double stdDev=0;
foreach(double v in dataList) {
mean += v;
stdDev += v*v;
}
mean /= N;
stdDev = Math.Sqrt((stdDev - N * mean * mean) / (N - 1));
Bookmarks