编译一个拟合数据曲线的脚本
这个任务可以使用 Python 的 NumPy 和 Matplotlib 库完成。以下是一个简单的脚本,它使用多项式拟合来拟合数据曲线:
import numpy as np
import matplotlib.pyplot as plt
# 输入数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
# 多项式拟合
p = np.polyfit(x, y, deg=2)
fit_y = np.polyval(p, x)
# 绘制拟合曲线和原始数据
plt.plot(x, y, 'o', label='原始数据')
plt.plot(x, fit_y, label='拟合曲线')
plt.legend()
plt.show()
在这个例子中,我们使用 np.polyfit 函数来进行多项式拟合,其中 deg=2 指定了使用二次多项式。然后,我们使用 np.polyval 函数来计算拟合曲线的值。最后,我们使用 Matplotlib 库来绘制原始数据和拟合曲线。
你可以根据自己的数据和需求来修改代码中的参数和函数。
原文地址: https://www.cveoy.top/t/topic/bhti 著作权归作者所有。请勿转载和采集!