简体   繁体   中英

Python indexing for central differencing

I have a question about python indexing: I am trying to use central differencing to estimate 'dU' from an array 'U' and I'm doing this by initialising 'dU' with an array of 'nan' of length(U) and then applying central differencing such that dU(i) = (U(i+1) - U(i-1))/2 to the central elements. The output 'dU' array is currently giving me two 'nan' entries at the end of the vector. Can anyone explain why the second to last element isn't being updated?

import numpy as np
U= np.array([1,2,3,4,5,6])
dU = np.zeros(len(U))
dU[:] = np.NAN
dU[1:-2] = (U[2:-1]-U[0:-3])/2

>>> dU
array([ nan,   1.,   1.,   1.,  nan,  nan])

要包含倒数第二个元素,您需要:

dU[1:-1] = (U[2:]-U[0:-2])/2

Doesn't answer your question, but as a helpful tip, you can just use numpy.gradient

>>> np.gradient(np.array([1,2,3,4,5,6]))
>>> array([ 1.,  1.,  1.,  1.,  1.,  1.])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM