Sunday, December 14, 2008

Derivative in Python/Numpy


Though I don't use it very often, the following little snippet for python/numpy can be useful for the determination of an array's derivative. The image shows the use of this function to determine the derivative of a particular array to aid in a classical peak picking scheme using zero-crossings. Oddly enough there doesn't seem to be an explicit function to do this in scipy and/or numpy--or at least not that I'm aware. If anyone has a better solution please share.


def derivative(y_data):
'''calculates the 1st derivative'''
y = (y_data[1:]-y_data[:-1])
dy = y/2 #scaling factor that is not necessary but useful for my application
#one more value is added because the length
# of y and dy are 1 less than y_data
return N.append(dy,dy.mean())

1 comment:

... said...

How is this different from numpy.diff(x)?