簡體   English   中英

使用numpy評估函數

[英]Evaluating a function using numpy

評估函數時,返回部分的意義是什么? 為什么這是必要的?

您給出答案。 x[0]-1.0 ,並且您想要將值放在數組的中間。`np.linspace是構建這樣的一系列值的好函數:

def f1(x):
    g = np.sin(math.pi*np.exp(-x))
    return g

n = 1001 # odd !
x=linspace(-1,1,n) #x[n//2] is 0
f1x=f1(x)
df1=np.diff(f1(x),1)
dx=np.diff(x)

df1dx = - math.pi*np.exp(-x)*np.cos(math.pi*np.exp(-x))[:-1] # to discard last element

# In [3]: np.allclose(df1/dx,df1dx,atol=dx[0])
# Out[3]: True

另一個技巧是,無循環的numpy數組更有效,更易讀。

您的假設是正確的: dfdx[0]實際上是該數組中的第一個值,因此根據您的代碼,它對應於評估x=-1.0處的導數。

要知道x等於0的正確索引,您必須在x數組中尋找它。

下面是找到這種情況的一種方法,我們在其中找到| x-0 |的值的索引。 使用argmin是最小的(因此本質上是x = 0,但float運算需要采取一些預防措施):

index0 = np.argmin(np.abs(x-0))

然后我們得到我們想要的,dfdx在x為0的索引處:

print dfdx[index0]

關於浮點運算技巧的另一種但不太可靠的方法是執行以下操作:

# we make a boolean array that is True where x is zero and False everywhere else
bool_array = (x==0) 
# Numpy alows to use a boolean array as a way to index an array
# Doing so will get you the all the values of dfdx where bool_array is True 
# In our case that will hopefully give us dfdx where x=0
print dfdx[bool_array] 
# same thing as oneliner
print dfdx[x==0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM