所以我正在尝试使用python来做方程函数
这是我的代码:
def var_method_1(x):
n = len(x)
return [sum(i**2)-1/n*(sum(i)**2) for i in x]/(n-1)
所以这是调用代码,这是很长的调用代码,不确定是哪个部分导致了错误
# Test cell: `exercise_1_test`
from random import gauss
from statistics import variance
n = 100000
mu = 1e7
sigma = 1.0
for _ in range(5): # 5 trials
X = [gauss(mu, sigma) for _ in range(n)]
var_py = variance(X)
try:
del variance
var_you_0 = var_method_0(X)
var_you_1 = var_method_1(X)
except NameError as n:
if n.args[0] == "name 'variance' is not defined":
assert False, "Did you try to use `variance()` instead of implementing it from scratch?"
else:
raise n
finally:
variance = SAVE_VARIANCE
rel_diff_0 = abs(var_you_0 - var_py) / var_py
rel_diff_1 = abs(var_you_1 - var_py) / var_py
print("\nData: n={} samples from a Gaussian with mean {} and standard deviation {}".format(n, mu, sigma))
print("\tPython's variance function computed {}.".format(var_py))
print("\tvar_method_0(X) computed {}, with a relative difference of {}.".format(var_you_0, rel_diff_0))
assert rel_diff_0 <= n*(2.0**(-52)), "The relative difference is larger than expected."
print("\tvar_method_1(X) computed {}, with a relative difference of {}.".format(var_you_1, rel_diff_1))
assert rel_diff_1 > n*(2.0**(-52)), "The relative difference is smaller than expected!"
print("\n(Passed!)")
这是错误:
答案 0 :(得分:0)
错误的回报。
return (sum([i**2 for i in x]) - sum(x)**2/n)/(n-1)
答案 1 :(得分:0)
sum
采用可迭代方式,例如列表求和。在这种情况下,您给sum设置了一个浮点数(假设x是您对x进行迭代时的浮点数向量)。