from scipy import interpolate import matplotlib.pyplot as plt import numpy as np def f(x): x_points = [ 0, 1, 2, 3, 4, 5] y_points = [0,1,4,9,16,25] #實際函數關係式爲:y=x^2 xnew = np.linspace(min(x_points),max(x_points),100) #新制做100個x值。(等差、list[]形式存儲) tck = interpolate.splrep(x_points, y_points) ynew = interpolate.splev(xnew, tck) #經過擬合的曲線,計算每個輸入值。(100個結果,list[]形式存儲) plt.scatter(x_points[:], y_points[:], 25, "red") #繪製散點 plt.plot(xnew,ynew) #繪製擬合曲線圖 plt.show() return interpolate.splev(x, tck) print(f(10))
結果:html
參考資料:python
https://stackoverflow.com/questions/31543775/how-to-perform-cubic-spline-interpolation-in-python函數
https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.htmlspa