LINQ - Calculate average and standard deviation in one go
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: LINQ - Calculate average and standard deviation in one go

  1. #1
    Join Date
    Jan 2010
    Posts
    3

    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?

  2. #2
    Join Date
    Apr 2007
    Location
    Florida
    Posts
    403

    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();
            }
        }
    }

  3. #3
    Join Date
    Jan 2010
    Posts
    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
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center