# 用户自定义函数代码实现 import numpy as np import matplotlib.pyplot as plt
defcalcAB(x,y): n = len(x) sumX,sumY,sumXY,sumXX =0,0,0,0 for i inrange(0,n): sumX += x[i] sumY += y[i] sumXX += x[i]*x[i] sumXY += x[i]*y[i] a = (n*sumXY -sumX*sumY)/(n*sumXX -sumX*sumX) b = (sumXX*sumY - sumX*sumXY)/(n*sumXX-sumX*sumX) return a,b,
# xi = [1,2,3,4,5,6,7,8,9,10] # yi = [10,11.5,12,13,14.5,15.5,16.8,17.3,18,18.7] xi = [1,2,3,4,5,6,7,8,9,10] # yi = [1 for i in range(10)] yi = [0] * 10 print(yi) for num in xi: yi[num -1] = num*1.201030944 + 9.8678999766 a,b=calcAB(xi,yi) print("y = 1.201030944*x + 9.8678999766", '\n', "f(x;a,b) = (a)%3.5fx + (b)%3.5f" %(a,b)) x = np.linspace(0,10) y = a * x + b plt.plot(x,y,'red', label='fitting curve') plt.scatter(xi,yi, label='primitive curve') plt.legend(loc='right') plt.title('last square method fitting curve') plt.show()
plt.plot(x,y,'o',label='idea curve',markersize=10) plt.plot(x,a*x+b,'r',label='fitting curve') plt.legend(loc='upper left') plt.title(' the least-squares solution to a linear matrix equation.') plt.show()