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即可:
print('三次多项式拟合曲线系数:', a)
- 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) print('Third order polynomial fitted curve coefficients:', a)
构建拟合曲线
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='Raw data') plt.plot(t_fit, T_fit, label='Fitting the curve') plt.legend() plt.xlabel('Times/h') plt.ylabel('Temperature /℃') plt.show() plt.savefig('zuixiaoercheng2.png') 解释以上代码每一步
- Assistant
- 导入需要使用的库:
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是一个24行4列的矩阵,第一列都是1,第二列是时间t,第三列是时间t的平方,第四列是时间t的立方。
- 求解最小二乘解a:
a = np.linalg.inv(A.T.dot(A)).dot(A.T).dot(T)
这里使用了最小二乘法,根据公式求解矩阵a的值。
- 构建拟合曲线:
t_fit = np.linspace(1, 24, 200) T_fit = a[0] + a[1]*t_fit + a[2]*t_fit2 + a[3]*t_fit3
这里使用了linspace函数生成200个等间隔的时间点,然后根据多项式函数的系数a计算对应的温度值。
- 绘制数据点和拟合曲线:
plt.plot(t, T, 'o', label='Raw data') plt.plot(t_fit, T_fit, label='Fitting the curve') plt.legend() plt.xlabel('Times/h') plt.ylabel('Temperature /℃') plt.show() plt.savefig('zuixiaoercheng2.png')
使用Matplotlib库创建图表,其中plt.plot用于绘制数据点和拟合曲线,plt.xlabel和plt.ylabel用于设置x轴和y轴的标签,plt.show用于显示图表,plt.savefig用于保存图表。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.