Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derivative of an array in python?

Currently I have two numpy arrays: x and y of the same size.

I would like to write a function (possibly calling numpy/scipy... functions if they exist):

def derivative(x, y, n = 1):
    # something
    return result

where result is a numpy array of the same size of x and containing the value of the n-th derivative of y regarding to x (I would like the derivative to be evaluated using several values of y in order to avoid non-smooth results).

like image 966
Vincent Avatar asked Nov 18 '13 09:11

Vincent


2 Answers

This is not a simple problem, but there are a lot of methods that have been devised to handle it. One simple solution is to use finite difference methods. The command numpy.diff() uses finite differencing where you can specify the order of the derivative.

Wikipedia also has a page that lists the needed finite differencing coefficients for different derivatives of different accuracies. If the numpy function doesn't do what you want.

Depending on your application you can also use scipy.fftpack.diff which uses a completely different technique to do the same thing. Though your function needs a well defined Fourier transform.

There are lots and lots and lots of variants (e.g. summation by parts, finite differencing operators, or operators designed to preserve known evolution constants in your system of equations) on both of the two ideas above. What you should do will depend a great deal on what the problem is that you are trying to solve.

The good thing is that there is a lot of work has been done in this field. The Wikipedia page for Numerical Differentiation has some resources (though it is focused on finite differencing techniques).

like image 70
Ben Whale Avatar answered Sep 18 '22 01:09

Ben Whale


The findiff project is a Python package that can do derivatives of arrays of any dimension with any desired accuracy order (of course depending on your hardware restrictions). It can handle arrays on uniform as well as non-uniform grids and also create generalizations of derivatives, i.e. general linear combinations of partial derivatives with constant and variable coefficients.

like image 30
maroba Avatar answered Sep 22 '22 01:09

maroba