NumPy 中有多种插值方法可供选择,主要是通过 numpy.interp()
和 numpy.interpolate.interp1d
来实现的。以下是一些常见的插值方法以及它们的含义:
Linear Interpolation (线性插值):
Nearest-neighbor Interpolation (最近邻插值):
Polynomial Interpolation (多项式插值):
Spline Interpolation (样条插值):
Cubic Spline Interpolation (三次样条插值):
下面用Python做一个直观的图形展示比较,提前安装包numpy, matplotlib和scipy
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
# 创建一些示例数据点
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0, 1, 0.5, 1.5, 1, 0])
# 创建不同插值方法的函数
linear_interp = interp1d(x, y, kind="linear")
cubic_interp = interp1d(x, y, kind="cubic")
nearest_interp = interp1d(x, y, kind="nearest")
quadratic_interp = interp1d(x, y, kind="quadratic")
# 生成更密集的 x 值以便绘制平滑的曲线
x_new = np.linspace(0, 5, 100)
# 计算插值结果
y_linear = linear_interp(x_new)
y_cubic = cubic_interp(x_new)
y_nearest = nearest_interp(x_new)
y_quadratic = quadratic_interp(x_new)
# 创建图表
lw = 2
plt.figure(figsize=(8, 6))
plt.plot(x, y, "o", label="Original Data", markersize=10)
plt.plot(x_new, y_linear, label="Linear Interpolation", linestyle="--", linewidth=lw)
plt.plot(
x_new, y_cubic, label="Cubic Spline Interpolation", linestyle="-", linewidth=lw
)
plt.plot(
x_new,
y_nearest,
label="Nearest-neighbor Interpolation",
linestyle="-.",
linewidth=lw,
)
plt.plot(
x_new, y_quadratic, label="Quadratic Interpolation", linestyle=":", linewidth=lw
)
plt.legend()
plt.title("Comparison of Different Interpolation Methods")
plt.xlabel("X")
plt.ylabel("Y")
plt.grid(True)
# 更改图例标签为英文
plt.legend(
[
"Original Data",
"Linear Interpolation",
"Cubic Spline Interpolation",
"Nearest-neighbor Interpolation",
"Quadratic Interpolation",
]
)
plt.show()