Numpy: numerical derivatives - tiagopereira/python_tips GitHub Wiki

Numpy: numerical derivatives

One dimension

You have a function and perhaps its abscissa and you want to calculate the numerical derivative. This is, in the classical sense:

f' = (y[i+1]-y[i])/(x[i+1]-x[i]),

evaluated at a position (i+1)/2. The term y[i+1]-y[i] can be quickly calculated with numpy's diff function:

d = N.diff(y)

If the spacing in x is constant, then x[i+1]-x[i] is fixed and you just need to multiply this d by that factor to get the derivative. If it is not, then the derivative will be:

d = N.diff(y)/N.diff(x)

Again, this will give you the derivative evaluated at the midpoints of the abscissa, which can be calculated like:

xd = (x[1:]+x[:-1])/2.

Multi-dimension

For an equally spaced grid you can use numpy's gradient function:

d = N.gradient(f,[spacing_x,spacing_y,spacing_z,...])

If the grid is not equally spaced then you need to do it manually!