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?
source
share