我想知道是否可以计算一些数字的平均值,如果我有这个:
int currentCount = 12; float currentScore = 6.1123 (this is a range of 1 <-> 10).
现在,如果我收到另一个分数(比方说4.5),我可以重新计算平均值,所以它会是这样的:
int currentCount now equals 13 float currentScore now equals ?????
或者这是不可能的,我仍然需要记住分数列表?
以下公式允许您根据需要跟踪存储的平均值和计数的平均值.
currentScore = (currentScore * currentCount + newValue) / (currentCount + 1) currentCount = currentCount + 1
这取决于您的平均值目前是您的总和除以计数.因此,您只需将平均值乘以平均值即可得到总和,添加新值并除以(计数+ 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 | +--------+-------+----------------------+----------------------+
我喜欢存储金额和计数.它每次都避免额外的乘法.
current_sum += input; current_count++; current_average = current_sum/current_count;