程序如下:
import matplotlib.pyplot as plt
import numpy as np
x_list = [466, 741, 950, 1422, 1634]
y_list = [7.04, 4.28, 3.40, 2.54, 2.13]
# x_list = [0, 1, 3, 5]
# y_list = [1, 2, 4, 8]
l_mat11 = len(x_list)
l_mat12 = l_mat21 = sum(x for x in x_list)
l_mat22 = sum(x * x for x in x_list)
r_mat1 = sum(y for y in y_list)
r_mat2 = sum(x * y for x, y in zip(x_list, y_list))
l_mat = np.asmatrix([[l_mat11, l_mat12], [l_mat21, l_mat22]])
r_mat = np.asmatrix([[r_mat1], [r_mat2]])
ans_mat = np.dot(l_mat.I, r_mat)
a0 = float(ans_mat[0])
a1 = float(ans_mat[1])
plot_x_list = [x for x in x_list]
plot_y_list = [a0 + a1 * x for x in plot_x_list]
plt.plot(plot_x_list, plot_y_list, c='b')
for x, y in zip(x_list, y_list):
plt.scatter(x, y, c='r')
plt.show()
编程结果