【问题标题】:Python statistics module returns different standard deviation than calculatedPython 统计模块返回的标准差与计算的不同
【发布时间】:2019-07-19 13:04:28
【问题描述】:

我有一个数字列表,我想计算其标准差。我使用两种不同的方法计算该值:1. 使用 Python 统计模块和 2. 使用标准差公式。结果是两个不同但有些接近的数字。统计模块计算标准差的方式有什么不同,还是与我的编码计算有关?我也不知道 math.sqrt() 在内部是如何工作的,但我认为它使用了某种近似值。

import statistics
import math    

def computeSD_S(variable):
    # Open the file and read the values in the column specified
    var_list = openAndReadVariable(variable)
    # Try to compute the median using the statistics module and print an error if a string is used as input
    try:
        st_dev = statistics.stdev(var_list)
        return st_dev
    except TypeError:
        return 'Variable values must be numerical.'

def computeSD_H(variable):
    # Open the file and read the values in the column specified
    var_list = openAndReadVariable(variable)
    sum = 0
    # Try to compute the standard deviation using this formula and print an error if a string is used as input
    try:
        # Find the mean
        mean = statistics.mean(var_list)
        # Sum the squared differences
        for obs in var_list:
            sum += (obs-mean)**2
        # Take the square root of the sum divided by the number of observations
        st_dev = math.sqrt(sum/len(var_list))
        return st_dev
    except TypeError:
        return 'Variable values must be numerical.'

variable = 'Total Volume'
st_dev = computeSD_S(variable)
print('Standard Deviation', st_dev)
st_dev = computeSD_H(variable)
print('Standard Deviation', st_dev)

结果输出:

Standard Deviation 3453545.3553994712
Standard Deviation 3453450.731237387

除了使用统计模块计算平均值之外,我还手动计算了平均值并获得了相同的结果。

【问题讨论】:

    标签: python


    【解决方案1】:

    什么为什么

    您自己的算法除以数组中的元素数量,而不是数组中的元素数量 - 1。

    现在为什么你应该除以 N-1 而不是 N?

    This post 似乎有一个很好的解释,您可以找到更多资源来解释为什么标准差的公式除以 N-1 而不是 1。

    如果我们查看标准偏差文档,我们可以看到:

    statistics.stdev(data, xbar=None)

    返回样本标准差(样本方差的平方根)。

    它计算 sample 标准差(也就是除以 N-1)。解决方案 1 是通过修改除法将您的函数与 stdev 匹配。

    解决方案 2,将 stdev 替换为 pstdev

    statistics.pstdev(data, mu=None)

    返回总体标准差(总体方差的平方根)。

    pstdev 计算总体标准差,换句话说,与您当前函数计算的相同。

    【讨论】:

    • 这是答案,谢谢。只需从观察次数中减去 1 就可以了,因为这是一个样本,应该这样对待。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2020-01-28
    • 2019-09-17
    • 2014-05-06
    相关资源
    最近更新 更多