考虑以下 Python 程序:
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
# Define your four data points
x = np.array([0, 1, 2, 3]) # x-coordinates of the points
y = np.array([0, 1, 0, 1]) # y-coordinates of the points
# Create the interpolation function with quadratic interpolation
f = interp1d(x, y, kind='quadratic')
# Generate a finer grid of x values for plotting
x_interp = np.linspace(min(x), max(x), 1000)
# Compute the corresponding y values using the interpolation function
y_interp = f(x_interp)
# Plot the data points and the interpolated curve
plt.scatter(x, y, label='Data Points')
plt.plot(x_interp, y_interp, label='Quadratic Interpolation')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Quadratic Interpolation with 4 Data Points')
plt.show()
这是结果图:
这不是二次多项式,而是三次多项式。
内部发生了什么
interp1d()
以及为什么生成的曲线不是二次曲线?
对于
scipy.interpolate.interp1d
,kind
参数指定要使用哪种 spline。当我们谈论使用样条线插值时,这通常意味着它是分段插值。
因此,在这种情况下,通过选择二次插值方法,每两个点将通过二次函数连接。现在,如果我们就这样离开问题,它将是未定义的(变量多于方程),因此可以使用边界条件来处理(我不会讨论)。
如果您想使用单个二次方程对数据进行插值,则会遇到问题,因为二次方程由 3 个点指定,而您有 4 个点。相反,正如评论中提到的,您必须执行曲线拟合(即回归),而不是插值。