Average function without overflow exception

后端 未结 18 1722
一生所求
一生所求 2021-02-12 14:58

.NET Framework 3.5.
I\'m trying to calculate the average of some pretty large numbers.
For instance:

using System;
using System.Linq;

class Program
{
           


        
18条回答
  •  离开以前
    2021-02-12 15:46

    If you're just looking for an arithmetic mean, you can perform the calculation like this:

    public static double Mean(this IEnumerable source)
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
    
        double count = (double)source.Count();
        double mean = 0D;
    
        foreach(long x in source)
        {
            mean += (double)x/count;
        }
    
        return mean;
    }
    

    Edit:

    In response to comments, there definitely is a loss of precision this way, due to performing numerous divisions and additions. For the values indicated by the question, this should not be a problem, but it should be a consideration.

提交回复
热议问题