-
Notifications
You must be signed in to change notification settings - Fork 8
Numpy: numerical derivatives
tiagopereira edited this page Aug 30, 2011
·
1 revision
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.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!