Eug*_*ene 1 python math conditional bioinformatics
我正在定义一个计算列表标准偏差的函数.有时候这个列表的平均值是负数,所以我的函数不能取负数的平方根,给我一个错误.
这看起来很简单,我只是想不起来.我想为我的函数写一个条件,如果有一个负数,则乘以-1,因为不能取负数的平方根.
我怎么写这个陈述?
def stdevValue(lst):
"""calculates the standard deviation of a list of numbers
input: list of numbers
output: float that is the standard deviation
"""
stdev = 0
stdevCalc = (((sum(lst) - (meanValue(x)))/(len(lst)-1)))**0.5
stdev += stdevCalc
return stdev
Run Code Online (Sandbox Code Playgroud)
Gre*_*ill 16
您似乎误用了标准差的公式.您根本不需要处理负数平方根的情况.在求和之前,您需要对值和均值之间的每个差异进行平方,如下所示:
def stdevValue(lst):
m = meanValue(x) # wherever this comes from
return (sum((x - m) ** 2 for x in lst) / len(lst)) ** 0.5
Run Code Online (Sandbox Code Playgroud)
这确保总和是非负的,因此您可以取平方根而不关心负值.(如果您想要样本标准偏差,除以(len(lst) - 1)).
有关更多信息和示例,请参阅Wikipedia关于标准偏差的文章.