I have a function to compute the finite difference of a 1d np.array and I want to extrapolate to a n-d array.
The function is like this:
def fpp_fourth_order_term(U):
"""Returns the second derivative of fourth order term without the interval multiplier."""
# U-slices
fm2 = values[ :-4]
fm1 = values[1:-3]
fc0 = values[2:-2]
fp1 = values[3:-1]
fp2 = values[4: ]
return -fm2 + 16*(fm1+fp1) - 30*fc0 - fp2
It is missing the 4th order multiplier (1/(12*h**2)
), but that is ok, because I will multiply when grouping the terms.
I would love to extend it as a N-dimensional. For that I would do the following changes:
def fpp_fourth_order_term(U, axis=0):
"""Returns the second derivative of fourth order term along an axis without the interval multiplier."""
# U-slices
But here is the issue
fm2 = values[ :-4]
fm1 = values[1:-3]
fc0 = values[2:-2]
fp1 = values[3:-1]
fp2 = values[4: ]
This works fine in 1D, if is 2D along first axis for example I would have to change for something like:
fm2 = values[:-4,:]
fm1 = values[1:-3,:]
fc0 = values[2:-2,:]
fp1 = values[3:-1,:]
fp2 = values[4:,:]
But along the second axis would be:
fm2 = values[:,:-4]
fm1 = values[:,1:-3]
fc0 = values[:,2:-2]
fp1 = values[:,3:-1]
fp2 = values[:,4:]
The same applies to 3d, but has 3 possibilities and goes on and on. The return always works if the neighbors are correctly set.
return -fm2 + 16*(fm1+fp1) - 30*fc0 - fp2
Of course axis
cannot be larger than len(U.shape)-1
(I call this the dimension, is there any way to extract instead this snippet?
How can I do a elegant and pythonic approach for this coding problem?
Is there a better way to do it?
PS: Regarding np.diff
and np.gradient
, those do not work since the first one is first order and the second one is second order, I'm doing a fourth order approximation. In fact soon I finish this problem I will also generalize the order. But yes, I want to be able to do in any axis as np.gradient
do.