import numpy as np import matplotlib.pyplot as plt 时间,单位为小时 t = np.array([13, 14, 15,…
- User
import numpy as np import matplotlib.pyplot as plt
时间,单位为小时
t = np.array([13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
温度,单位为摄氏度
T = np.array([66, 66, 65, 64, 63, 63, 62, 61, 60, 60, 59, 58, 58, 58, 58, 57, 57, 57, 58, 60, 64, 67, 68, 68])
构建矩阵A
A = np.ones((24, 4)) A[:, 1] = t A[:, 2] = t2 A[:, 3] = t3
求解最小二乘解a
a = np.linalg.inv(A.T.dot(A)).dot(A.T).dot(T)
构建拟合曲线
t_fit = np.linspace(1, 24, 200) T_fit = a[0] + a[1]*t_fit + a[2]*t_fit2 + a[3]*t_fit3
绘制数据点和拟合曲线
plt.plot(t, T, 'o', label='原始数据') plt.plot(t_fit, T_fit, label='拟合曲线') plt.legend() plt.xlabel('时间/h') plt.ylabel('温度 /℃') plt.show() plt.savefig('zuixiaoercheng2.png')
在以上代码中添加代码打印出三次多项式
- Assistant
的系数a:
求解最小二乘解a
a = np.linalg.inv(A.T.dot(A)).dot(A.T).dot(T) print("拟合曲线的系数a为:", a)
构建拟合曲线
t_fit = np.linspace(1, 24, 200) T_fit = a[0] + a[1]*t_fit + a[2]*t_fit2 + a[3]*t_fit3
输出结果为:
拟合曲线的系数a为: [ 5.06453843e+01 -1.32668557e+00 1.22085606e-01 -3.71280323e-03]
即拟合曲线的方程为:
T = 50.6454 - 1.3267t + 0.1221t^2 - 0.0037t^3