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
!
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
!
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()
I'm assuming this is what you meant:
>>> from __future__ import division
>>> x = [.1,.2,.5,.6,.7,.8,.9]
>>> y = [1,2,3,4,4,5,6]
>>> from itertools import izip
>>> def pairwise(iterable): # question 5389507
... "s -> (s0,s1), (s2,s3), (s4, s5), ..."
... a = iter(iterable)
... return izip(a, a)
...
>>> for ((a, b), (c, d)) in zip(pairwise(x), pairwise(y)):
... print (d - c) / (b - a)
...
10.0
10.0
10.0
>>>
That is, define dx
as the difference between adjacent elements in x
.
numpy.diff(x) computes
the difference between adjacent elements in x
just like in the answer by @tsm. As a result you get an array which is 1 element shorter than the original one. This of course makes sense, as you can only start computing the differences from the first index (1 "history element" is needed).
>>> x = [1,3,4,6,7,8]
>>> dx = numpy.diff(x)
>>> dx
array([2, 1, 2, 1, 1])
>>> y = [1,2,4,2,3,1]
>>> dy = numpy.diff(y)
>>> dy
array([ 1, 2, -2, 1, -2])
Now you can divide those 2 resulting arrays to get the desired derivative.
>>> d = dy / dx
>>> d
array([ 0.5, 2. , -1. , 1. , -2. ])
If for some reason, you need a relative (to the y-values) growth, you can do it the following way:
>>> d / y[:-1]
array([ 0.5 , 1. , -0.25 , 0.5 , -0.66666667])
Interpret as 50% growth, 100% growth, -25% growth, etc.
Full code:
import numpy
x = [1,3,4,6,7,8]
y = [1,2,4,2,3,1]
dx = numpy.diff(x)
dy = numpy.diff(y)
d = dy/dx