prevent long running averaging from overflow? <p>suppose I want to calculate average value of a data-set such as</p> <pre><code>class Averager { float total; size_t count; float addData (float value) { this-&gt;total += value; return this-&gt;total / ++this-&gt;count; } } </code></pre> <p>sooner or later the <code>total</code> or <code>count</code> value will overflow, so I make it doesn't remember the total value by :</p> <pre><code>class Averager { float currentAverage; size_t count; float addData (float value) { this-&gt;currentAverage = (this-&gt;currentAverage*count + value) / ++count; return this-&gt;currentAverage; } } </code></pre> <p>it seems they will overflow longer, but the multiplication between <code>average</code> and <code>count</code> lead to overflow problem, so next solution is:</p> <pre><code>class Averager { float currentAverage; size_t count; float addData (float value) { this-&gt;currentAverage += (value - this-&gt;currentAverage) / ++count; return this-&gt;currentAverage; } } </code></pre> <p>seems better, next problem is how to prevent <code>count</code> from overflow?</p>