Skip to content

Instantly share code, notes, and snippets.

@biplab37
Last active November 16, 2022 10:51
Show Gist options
  • Save biplab37/c449e76dbdf2731e803540e73ff651ca to your computer and use it in GitHub Desktop.
Save biplab37/c449e76dbdf2731e803540e73ff651ca to your computer and use it in GitHub Desktop.

Numerical Derivative

In python

Using finite Difference

import numpy as np

def deriv(x,y):
  return np.diff(y)/np.diff(x)

the above function works if the inputs are both numpy arrays of same size. The returned array has 1 less elements than the input arrays.

If the input arrays have some small noise than taking the naive finite difference derivative will result in answers which are almost useless. One can use Savgol filter to smoothen out that noise while taking derivatives.

from scipy.signal import savgol_filter

def deriv_savgol(x,y,window=25,polyorder=1):
  dy = savgol_filter(y,window,polyorder,deriv=1)
  dx = savgol_filter(x,window,polyorder,deriv=1)
  return dy/dx

Note that this method returns array of same size as the input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment