Average function without overflow exception

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

    Let Avg(n) be the average in first n number, and data[n] is the nth number.

    Avg(n)=(double)(n-1)/(double)n*Avg(n-1)+(double)data[n]/(double)n
    

    Can avoid value overflow however loss precision when n is very large.

提交回复
热议问题