记录一下作业
import math
a = [23,23,27,27,39,41,47,49,50,52,54,54,56,57,58,58,60,61]
b =[9.5,26.5,7.8,17.8,31.4,25.9,27.4,27.2,31.2,34.6,42.5,28.8,33.4,30.2,34.1,32.9,41.2,35.7]
"""a1 = input("请输入年龄:")
a = [int(i) for i in a1.split()]
b1 = input("请输入%fat")
b = [float(j) for j in b1.split()]
"""
def mean(x):
return sum(x) / len(x)
def de_mean(x):
x_bar = mean(x)
return [x_i - x_bar for x_i in x]
def dot(v, w):
return sum(v_i * w_i for v_i, w_i in zip(v, w))
def sum_of_squares(v):
return dot(v, v)
def variance(x):
n = len(x)
deviations = de_mean(x)
return sum_of_squares(deviations) / (n - 1)
def standard_deviation(x):
return math.sqrt(variance(x))
def covariance(x, y):
n = len(x)
return dot(de_mean(x), de_mean(y)) / (n-1)
def correlation(x, y):
stdev_x = standard_deviation(x)
stdev_y = standard_deviation(y)
if stdev_x > 0 and stdev_y > 0:
return covariance(x, y) / stdev_x / stdev_y
else:
return 0
print(a)
print(b)
print("r=", correlation(a, b))