2016-02-16 30 views
3

假設我們有嚴格越來越多x數組給出採樣功能y = f(x)和陣列y值與numpy的函數

import numpy as np 
import matplotlib.pyplot as plt 

x = np.linspace(0, 4, 11)  # [ 0. 0.4 0.8 1.2 1.6 2. 2.4 2.8 3.2 3.6 4. ] 
y = np.array([0, 1, 2, 3, 3, 1, -1, -4, -5, -6, -7]) 
plt.plot(x,y); plt.show() 

有一種自然的方式,與numpy的,以例如計算值f(1.2)f(2.3)
可以通過最近的鄰居(f(2.3)應該是f(2.4) = -1)或通過線性插值。

enter image description here

這種方法將工作,但會相當unpythonic:第一手動查找i,使得距離abs(x[i]-2.2)是最小的,然後返回y[i]。我可以想象numpy有一個內置的功能呢?

+5

你將有更具體的瞭解你的意思是*什麼「計算值'F(1.2 )'「*。嚴格地說,你的函數只定義在'x'中給出的值上,所以如果你想估計其他任意位置的值,那麼你需要對它進行插值。有很多方法可以執行插值,例如最近鄰居,線性,立方體等。看看['np.interp'](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.interp.html)和['scipy.interpolate'](http://docs.scipy.org/doc/scipy/reference/interpolate.html)。 –

+0

@ali_m我編輯並補充說,只要效率很高(我有幾百萬個採樣點要在短時間內處理),對我來說,最接近相鄰或線性插值都可以。 – Basj

+0

@Basj如果最近鄰居是好的,並且性能是一個問題,那麼爲什麼你不要把x舍入到最近的可用值呢?否則,您的問題已在上述ali_m的評論中得到有效回答。 – kazemakase

回答

0

如果可視化的插值是目標,那麼只需繪製函數就可以實現。 Numpy在數據點之間繪製線條,這相當於線性插值。

但是,如果要使用插值,則可以使用np.interp進行線性插值,或使用scipy.interpolate的某些函數進行任何類型的插值。最後,您可以通過簡單地舍入索引來執行最近鄰插值。

import numpy as np 
import matplotlib.pyplot as plt 

x = np.linspace(0, 4, 11)  # [ 0. 0.4 0.8 1.2 1.6 2. 2.4 2.8 3.2 3.6 4. ] 
y = np.array([0, 1, 2, 3, 3, 1, -1, -4, -5, -6, -7]) 

xi = np.linspace(0, 4, 1000) 

# a) nearest neighbor rounding 
dx = x[1] - x[0] 
i = np.round(xi/dx).astype(dtype=int) 
y1 = y[i] 

# b) linear interpolation 
y2 = np.interp(xi, x, y) 

plt.plot(x, y, '.', label='original points') 
plt.plot(xi, y1, label='rounding (nearest neighbor)') 
plt.plot(xi, y2, label='linear interpolation') 
plt.legend(loc='best') 
plt.show() 

enter image description here

0

定爲由@ali_m註釋解決方案的工作很好:

np.interp(1.2, x, y) # 3.0 
np.interp(2.3, x, y) # -0.5 
np.interp(2.4, x, y) # -1