【发布时间】: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