
February 5th, 2010, 12:21 PM
#1
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)/(n1) ) 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?

February 5th, 2010, 12:32 PM
#2
Re: LINQ  Calculate average and standard deviation in one go
May have missed the formula's order of operations, but here's my attempt at it:
Code:
namespace MathHelp
{
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
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 };
double average = 0;
double total = 0;
double deviation = 0;
for (int i = 0; i < values.Count; i++)
{
total += values[i];
if (i == values.Count  1)
{
average = total / values.Count;
deviation = Math.Sqrt(((Math.Pow(total, 2))  (values.Count * average))) / values.Count  1;
}
}
Console.WriteLine("Average: {0}", average);
Console.WriteLine("Deviation: {0}", deviation);
Console.ReadLine();
}
}
}

February 5th, 2010, 01:18 PM
#3
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));
Posting Permissions
 You may not post new threads
 You may not post replies
 You may not post attachments
 You may not edit your posts

Forum Rules

Click Here to Expand Forum to Full Width
This is a CodeGuru survey question.
Featured
