How do I compute the derivative of an array, y (say), with respect to another array, x (say) - both arrays from a certain experiment?
e.g.
y = [1,2,3,4,4,5,6]
and x = [.1,.2,.5,.6,.7,.8,.9]
;
I want to get dy/dx
!
Solving Derivatives in PythonSymPy has lambdify function to calculate the derivative of the function that accepts symbol and the function as argument.
Use numpy.diff
If dx is constant
from numpy import diff dx = 0.1 y = [1, 2, 3, 4, 4, 5, 6] dy = diff(y)/dx print dy array([ 10., 10., 10., 0., 10., 10.])
dx is not constant (your example)
from numpy import diff x = [.1, .2, .5, .6, .7, .8, .9] y = [1, 2, 3, 4, 4, 5, 6] dydx = diff(y)/diff(x) print dydx [10., 3.33333, 10. , 0. , 10. , 10.]
Note that this approximated "derivative" has size n-1
where n
is your array/list size.
Don't know what you are trying to achieve but here are some ideas:
use numpy.gradient()
Please be aware that there are more advanced way to calculate the numerical derivative than simply using diff
. I would suggest to use numpy.gradient
, like in this example.
import numpy as np from matplotlib import pyplot as plt # we sample a sin(x) function dx = np.pi/10 x = np.arange(0,2*np.pi,np.pi/10) # we calculate the derivative, with np.gradient plt.plot(x,np.gradient(np.sin(x), dx), '-*', label='approx') # we compare it with the exact first derivative, i.e. cos(x) plt.plot(x,np.cos(x), label='exact') plt.legend()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With