【问题标题】:Continuous calculation of the mean of values?连续计算平均值?
【发布时间】:2019-07-31 15:45:07
【问题描述】:

在一段时间内我的应用程序中有一系列数字,例如:[10, 8, 11, 9, 10, 8, 8, 11, 9, 8, 10, 11]

我知道我可以用statistics.mean(x) 计算这些值的平均值,但这需要我存储我得到的所有值。

现在的问题是:有没有办法在每次我得到一个新值时计算所有值的平均值,而不存储每个值?

应该是这样的:

新值:10 -> 平均值:10

新值:8 -> 平均值:9

新值:11 -> 平均值:9,6

等等……

编辑:我可能只是将所有值相加并计算我得到了多少值..

【问题讨论】:

  • 适用于 Java 但算法相同:stackoverflow.com/questions/31904332/…
  • 您有正确的概念,总和和计数将始终允许您计算平均值。当新值出现时,将其添加到总和中并将计数增加 1

标签: python mean calculation continuous


【解决方案1】:

是的,只保留到目前为止的总和和数字的数量

def init_running_average():
    int total = 0
    int count = 0

    def add_number(x):
        nonlocal total, count

        count += 1
        total += x

        return total/count
    return add_number

avg = init_running_average()
print(avg(10)) # 10
print(avg(8)) # 9

【讨论】:

    猜你喜欢
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2012-06-19
    相关资源
    最近更新 更多