Prevent long averaging from overflow?

Suppose I want to calculate the average value of a dataset, for example

class Averager {
   float total;
   size_t count;
   float addData (float value) {
       this->total += value;
       return this->total / ++this->count;
   }
}

sooner or later, the value totalor countwill overflow, so I do this, I do not remember the general value:

class Averager {
   float currentAverage;
   size_t count;
   float addData (float value) {
       this->currentAverage = (this->currentAverage*count + value) / ++count;
       return this->currentAverage;
   }
}

it seems that they will overflow longer, but multiplying between averageand countwill lead to an overflow problem, so the following solution:

class Averager {
   float currentAverage;
   size_t count;
   float addData (float value) {
       this->currentAverage += (value - this->currentAverage) / ++count;
       return this->currentAverage;
   }
}

it seems better, the next problem is how to prevent countfrom overflow?

+4
source share
6 answers

Aggregate buckets.

, (MAXINT). , 10.

, , .

, . , , . 10 , , 100.

, "10s", "100s". "1000s" "10000s" . 10 x , .

+7

double total; unsigned long long count;. , , float.

+2

, , RAM .

0

. , " ". , ( 1 ). , . Java-, , , . , , , double, . , , , . , . MAX_INT, , , .

    public float calcAverageContinuous(int[] integers)
{
    float ave = 0;
    for (int i = 0; i < integers.length; i++) {
        ave += (((float)integers[i] - ave) / (float)(i + 1));
    }
    return ave;
}
0
source

Source: https://habr.com/ru/post/1756133/


All Articles