Can I calculate the average of these numbers?

人走茶凉 提交于 2019-12-04 21:22:24

问题


I was wondering if it's possible to calculate the average of some numbers if I have this:

int currentCount = 12;
float currentScore = 6.1123   (this is a range of 1 <-> 10).

Now, if I receive another score (let's say 4.5), can I recalculate the average so it would be something like:

int currentCount now equals 13
float currentScore now equals ?????

or is this impossible and I still need to remember the list of scores?


回答1:


The following formulas allow you to track averages just from stored average and count, as you requested.

currentScore = (currentScore * currentCount + newValue) / (currentCount + 1)
currentCount = currentCount + 1

This relies on the fact that your average is currently your sum divided by the count. So you simply multiply count by average to get the sum, add your new value and divide by (count+1), then increase count.

So, let's say you have the data {7,9,11,1,12} and the only thing you're keeping is the average and count. As each number is added, you get:

+--------+-------+----------------------+----------------------+
| 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 |
+--------+-------+----------------------+----------------------+



回答2:


I like to store the sum and the count. It avoids an extra multiply each time.

current_sum += input;
current_count++;
current_average = current_sum/current_count;



回答3:


It's quite easy really, when you look at the formula for the average: A1 + A2 + ... + AN/N. Now, If you have the old average and the N (numbers count) you can easily calculate the new average:

newScore = (currentScore * currentCount + someNewValue)/(currentCount + 1)



回答4:


You can store currentCount and sumScore and you calculate sumScore/currentCount.




回答5:


or... if you want to be silly, you can do it in one line :

 current_average = (current_sum = current_sum + newValue) / ++current_count;

:)




回答6:


float currentScore now equals (currentScore * (currentCount-1) + 4.5)/currentCount ?



来源:https://stackoverflow.com/questions/340376/can-i-calculate-the-average-of-these-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!