32

我如何计算一个数组y (比方说)相对于另一个数组 x (比方说)的导数 - 来自某个实验的两个数组?

例如

y = [1,2,3,4,4,5,6]x = [.1,.2,.5,.6,.7,.8,.9];

我想得到dy/dx

4

4 回答 4

43

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:

于 2013-10-18T21:14:20.810 回答
8

利用numpy.gradient()

请注意,有比简单地使用更高级的方法来计算数值导数diff。我建议使用numpy.gradient,就像在这个例子中一样。

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()
于 2021-02-16T10:57:56.883 回答
5

我假设这就是你的意思:

>>> 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
>>>

问题 5389507 链接

也就是说,定义dx为 中相邻元素之间的差异x

于 2013-05-30T17:01:48.970 回答
4

numpy.diff(x)计算

x中相邻元素之间的差异

就像@tsm 的回答一样。结果,您得到一个比原始数组短 1 个元素的数组。这当然是有道理的,因为您只能开始计算与第一个索引的差异(需要 1 个“历史元素”)。

>>> 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])

现在您可以划分这 2 个结果数组以获得所需的导数。

>>> d = dy / dx
>>> d
array([ 0.5,  2. , -1. ,  1. , -2. ])

如果由于某种原因,您需要相对(相对于 y 值)增长,您可以通过以下方式进行:

>>> d / y[:-1]
array([ 0.5       ,  1.        , -0.25      ,  0.5       , -0.66666667])

解释为 50% 增长、100% 增长、-25% 增长等。

完整代码:

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
于 2018-01-25T19:40:33.783 回答