我想通過有限差分計算導數,但請注意,我這里的步長為 2 個網格點。
這可以很容易地在for回圈中實作,但是速度很慢。由于我正在處理numpy陣列,因此我for通過陣列切片替換了回圈以顯著提高速度。然后我想測驗/比較,numpy.diff但使用它我得到了不同的結果。
import matplotlib.pyplot as plt
import numpy as np
# create some data
n = 100
x = np.linspace(0,2*np.pi,n)
y = np.linspace(0,2*np.pi,n)
X,Y = np.meshgrid(x,y)
Z = np.sin(X) * np.sin(Y)
# calculate centered finite difference using for loop
Z_diff1 = Z*.0
for ii in range(1,Z.shape[0]-1,2):
for jj in range(1,Z.shape[1]-1,2):
Z_diff1[ii,jj] = Z[ii-1, jj] - Z[ii 1,jj]
# calculate centered finite difference using array slicing
Z_diff2 = Z[:-2:2,::2] - Z[2::2,::2]
# calculate centered finite difference using numpy.diff
Z_diff3 = np.diff(Z[::2,::2], axis=0)
fig = plt.figure( figsize=(8,6) )
ax1 = fig.add_subplot( 1,4,1, aspect='equal' )
ax1.pcolormesh(Z)
ax1.set_title('original data')
ax2 = fig.add_subplot( 1,4,2, aspect='equal' )
ax2.pcolormesh(Z_diff1[1::2,1::2])
ax2.set_title('for loops')
ax3 = fig.add_subplot( 1,4,3, aspect='equal' )
ax3.pcolormesh(Z_diff2)
ax3.set_title('slicing')
ax4 = fig.add_subplot( 1,4,4, aspect='equal' )
ax4.pcolormesh(Z_diff3)
ax4.set_title('numpy.diff')
plt.show()
從圖中可以看出,結果numpy.diff看起來不同 - 我在這里錯過了什么?

uj5u.com熱心網友回復:
根據檔案,第一個差異是由out[i] = a[i 1] - a[i]沿給定軸給出的。
>>> a = np.array([1, 2, 3, 4, 5, 4, 3, 2, 1])
>>> np.diff(a[::2])
array([ 2, 2, -2, -2])
你在做相反的事情:
>>> a[:-2:2] - a[2::2]
array([-2, -2, 2, 2])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374266.html
標籤:Python 麻木的 for循环 numpy-ndarray numpy切片
上一篇:如何使用R字串Python回圈
