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(13, 24, 100) 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
代码运行结果如下图所示:
可以看出,拟合曲线很好地拟合了原始数据点。
- User
解释以上代码每一步
- Assistant
- 导入numpy和matplotlib.pyplot模块:
pythonimport numpy as np import matplotlib.pyplot as plt- 定义时间和温度数据:
pythont = 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:
pythonA = np.ones((24, 4)) A[:, 1] = t A[:, 2] = t**2 A[:, 3] = t**3这里定义了一个24行4列的矩阵A,其中第一列都是1,第二列是时间t,第三列是时间的平方t^2,第四列是时间的立方t^3。
- 求解最小二乘解a:
- User
T_fit = a[0] + a[1]*t_fit + a[2]*t_fit2 + a[3]*t_fit3 详细解释
- Assistant
这一行代码是用最小二乘法求得的曲线拟合方程的计算公式,用于计算t_fit数组对应的拟合温度T_fit数组。
根据最小二乘法求得的曲线拟合方程: