Average function without overflow exception

后端 未结 18 1781
一生所求
一生所求 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:32

    If you know approximately what the average will be (or, at least, that all pairs of numbers will have a max difference < long.MaxValue), you can calculate the average difference from that value instead. I take an example with low numbers, but it works equally well with large ones.

    // Let's say numbers cannot exceed 40.
    List numbers = new List() { 31 28 24 32 36 29 }; // Average: 30
    
    List diffs = new List();
    
    // This can probably be done more effectively in linq, but to show the idea:
    foreach(int number in numbers.Skip(1))
    {
        diffs.Add(numbers.First()-number);
    }
    // diffs now contains { -3 -6 1 5 -2 }
    
    var avgDiff = diffs.Sum() / diffs.Count(); // the average is -1
    
    // To get the average value, just add the average diff to the first value:
    var totalAverage = numbers.First()+avgDiff;
    

    You can of course implement this in some way that makes it easier to reuse, for example as an extension method to IEnumerable.

提交回复
热议问题