次のようなデータセットの平均値を計算したいとします。
class Averager {
float total;
size_t count;
float addData (float value) {
this->total += value;
return this->total / ++this->count;
}
}
遅かれ早かれortotal
値count
がオーバーフローするので、合計値を記憶しないようにします。
class Averager {
float currentAverage;
size_t count;
float addData (float value) {
this->currentAverage = (this->currentAverage*count + value) / ++count;
return this->currentAverage;
}
}
それらはより長くオーバーフローするようですが、との間の乗算はオーバーフローの問題average
にcount
つながるため、次の解決策は次のとおりです。
class Averager {
float currentAverage;
size_t count;
float addData (float value) {
this->currentAverage += (value - this->currentAverage) / ++count;
return this->currentAverage;
}
}
次の問題はcount
オーバーフローを防ぐ方法ですか?