我想通过给定值生成一个多项式方程并得到一个等式。然而,当我用给定的 x 值控制它时,我从等式中得到不同的值,这里是我的代码和输出:
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 2)
f = np.poly1d(z)
它给了我这个等式:-0.001416*x^2 + 0.1504*x + 1.72
输出
x expected(y) returned(y)
1 1 1.868984
2 4 2.015136
3 1 2.158456
9 3 2.9589040000000004
是我错了还是我读错了?
请您参考如下方法:
你好像误解了多项式拟合的概念。当您调用 polyfit(x, y, n) ,它的作用是为您提供最适合点集 (x, y) 的第 n 次(或更小)次多项式。因此,通过使用 n = 2 调用 polyfit,它会返回适合您给定的点的最佳二次多项式。此多项式只是您的集合的近似值,因此预计返回值与预期值不同,并且由于它们无法用二次多项式表示这一事实而变得更糟。
以下代码直观地演示了这是如何实现的。改变你的点,polyfit() 函数的 n 值,看看你是否能更好地理解这个概念:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 2)
f = np.poly1d(z)
x_fit = np.linspace(-100, 100, 1000)
y_fit = [f(_x) for _x in x_fit]
plt.plot(x, y)
plt.plot(x_fit, y_fit)
plt.show()
