import numpy as np
def cov(x,y):
if len(x) != len(y):
return
a_mean = np.mean(x)
b_mean = np.mean(y)
sum = 0
for i in range(0, len(x)):
sum += ((x[i] - a_mean) * (y[i] - b_mean))
return sum/(len(x))-1
import numpy as np
def cov(x,y):
if len(x) == len(y):
a_mean = np.mean(x)
b_mean = np.mean(y)
sum = 0
for i in range(0, len(x)):
sum += ((x[i] - a_mean) * (y[i] - b_mean))
return sum/(len(x)-1)
else:
return 'The length of two lists are not the same'
我对您的代码做了 2 处更改。
我的条件语句如果两个列表的长度相同找到协方差否则错误消息
我改变了分母中右括号的位置