from math import sqrt
def multipl(a, b):
sumofab = 0.0
for i in range(len(a)):
temp = a[i] * b[i]
sumofab += temp
return sumofab
def corrcoef(x, y):
n = len(x)
# 求和
sum1 = sum(x)
sum2 = sum(y)
# 求乘积之和
sumofxy = multipl(x, y)
# 求平方和
sumofx2 = sum([pow(i, 2) for i in x])
sumofy2 = sum([pow(j, 2) for j in y])
num = sumofxy - (float(sum1) * float(sum2) / n)
# 计算皮尔逊相关系数
den = sqrt((sumofx2 - float(sum1 ** 2) / n) * (sumofy2 - float(sum2 ** 2) / n))
return num / den
x = [3.0, 2.6, 4.3, 2.1, 1.1, 6.1, 4.8, 3.8, 3.4, 1.8, 4.6, 2.3, 3.1, 5.5, 0.7]
y = [22.3, 19.6, 31.3, 24.0, 17.3, 43.2, 36.4, 26.1, 26.2, 17.8, 31.3, 23.1, 27.5, 36.0, 14.1]
print(corrcoef(x, y))