Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compute the derivative of an array in python

Tags:

python

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!

like image 296
Adams Gwazah Avatar asked May 30 '13 16:05

Adams Gwazah


People also ask

Can you calculate a derivative in Python?

Solving Derivatives in PythonSymPy has lambdify function to calculate the derivative of the function that accepts symbol and the function as argument.


2 Answers

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:

  • If you are trying to make numerical differentiation maybe finite differences formulation might help you better.
  • The solution above is like a first-order accuracy approximation for the forward schema of finite differences with a non-uniform grid/array.
like image 86
iambr Avatar answered Sep 21 '22 17:09

iambr


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() 
like image 31
giotto Avatar answered Sep 23 '22 17:09

giotto