Hàm interp1d() của gói scipy.interpolate dùng để nội suy hàm 1-D. Nó nhận mảng giá trị x, y để xấp xỉ hàm y = f(x) rồi dùng nội suy tìm giá trị điểm mới.
Cú pháp
scipy.interpolate.interp1d(x, y)
Trong đó x là mảng 1-D giá trị thực, y là mảng N-D giá trị thực. Độ dài y theo trục nội suy phải bằng độ dài x.
Ví dụ 1
Xét ví dụ sau:
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.arange(0, 10)
y = np.exp(-x/5.0)
plt.subplot(1,2,1)
plt.title("Dữ liệu đầu vào X và Y")
plt.plot(x, y)
plt.subplot(1,2,2)
plt.title("Nội suy")
f = interpolate.interp1d(x, y)
x_new = np.arange(0, 7, 0.7)
y_new = f(x_new)
plt.plot(x_new, y_new, 's')
plt.show()
Kết quả
Hai subplot: bên trái dữ liệu gốc giảm exponencial, bên phải các điểm vuông nội suy tuyến tính mặc định.
Ví dụ 2
Ví dụ khác:
import matplotlib.pyplot as plt import numpy as np from scipy import interpolate plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.arange(0, 10) y = np.exp(-x**2/9.0) f = interpolate.interp1d(x, y) xnew = np.arange(0, 9, 1.2) plt.plot(x, y, 'o', xnew) plt.show()
Kết quả
Đồ thị dữ liệu gốc (tròn) và các điểm nội suy (mặc định tuyến tính) tại xnew.