以下公式允许您根据您的要求仅从存储的平均值和计数中跟踪平均值。
currentScore = (currentScore * currentCount + newValue) / (currentCount + 1)
currentCount = currentCount + 1
这取决于您的平均值当前是您的总和除以计数的事实。因此,您只需将计数乘以平均值即可得到总和,将新值相加并除以 (count+1),然后增加计数。
所以,假设你有数据{7,9,11,1,12}
,你唯一要保留的是平均值和计数。随着每个数字的添加,您会得到:
+--------+-------+----------------------+----------------------+
| Number | Count | Actual average | Calculated average |
+--------+-------+----------------------+----------------------+
| 7 | 1 | (7)/1 = 7 | (0 * 0 + 7) / 1 = 7 |
| 9 | 2 | (7+9)/2 = 8 | (7 * 1 + 9) / 2 = 8 |
| 11 | 3 | (7+9+11)/3 = 9 | (8 * 2 + 11) / 3 = 9 |
| 1 | 4 | (7+9+11+1)/4 = 7 | (9 * 3 + 1) / 4 = 7 |
| 12 | 5 | (7+9+11+1+12)/5 = 8 | (7 * 4 + 12) / 5 = 8 |
+--------+-------+----------------------+----------------------+