Average function without overflow exception

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

    I guess there has to be a compromise somewhere or the other. If the numbers are really getting so large then few digits of lower orders (say lower 5 digits) might not affect the result as much.

    Another issue is where you don't really know the size of the dataset coming in, especially in stream/real time cases. Here I don't see any solution other then the (previousAverage*oldCount + newValue) / (oldCount <- oldCount+1)


    Here's a suggestion:

    *LargestDataTypePossible* currentAverage;
    *SomeSuitableDatatypeSupportingRationalValues* newValue;
    
    *int* count;
    addToCurrentAverage(value){
     newValue = value/100000;
     count = count + 1;
     currentAverage = (currentAverage * (count-1) + newValue) / count;
    }
    
    getCurrentAverage(){
     return currentAverage * 100000;
    }
    

提交回复
热议问题