Partial Derivative in Python

I am slowly moving from C to Python. This time I need to calculate the partial derivatives numerically from a given grid. I know how to do this in C, so for now I just use the built-in adapter, i.e.

def dz(x,X,Y,Z,dx):
    y = numpy.zeros((X,Y,Z), dtype='double');
    code = """
            int i, j, k;
            for (i=0; i<X-1; i++){
                for(k=0; k<Y; k++){
                    for (j=0; j<Z; j++){
                        y[i,k,j] = (x[i+1, k, j] - x[i, k, j])/dx;
                        }
                    }
                }
            for (j=0; j<Z; j++){
                for(k=0; k<Y; k++){
                    y[X-1,k,j] = - x[X-1, k, j]/dx;
                    }
                }
        """
    weave.inline(code, ['x', 'y', 'dx', 'X', 'Y', 'Z'], \
                type_converters=converters.blitz, compiler = 'gcc');
    return y;

where xand yare the 3D-numpy arrays, as you can see, while the second cycle is the boundary conditions. Of course, I can implement the same logic in pure Python, but the code will be inefficient. It is interesting, however, if it is possible to calculate the partial derivative using pure numpy? I would appreciate any help anyone can provide.

+4
source share
3 answers

np.diff numpy:

y = np.empty_like(x)
y[:-1] = np.diff(x, axis=0) / dx
y[-1] = -x[-1] / dx

np.gradient, , .

+4

numpy, , :

y = np.empty_like(x)
y[:-1] = (x[1:] - x[:-1]) / dx
y[-1] = -x[-1] / dx

, :

y = np.empty_like(x)
y[:, :-1] = (x[:, 1:] - x[:, :-1]) / dx
y[:, -1] = -x[:, -1] / dx
+2
def dz(x,dx):
    y = numpy.zeros(x.shape, dtype='double')
    y[:-1] = (x[1:] - x[:-1]) / dx
    y[-1]  = -x[-1] / dx
    return y
+2
source

All Articles