Ada*_*zah 12 python python-2.7
我如何计算数组的导数y(比方说),相对于另一个数组,x(比如说) - 来自某个实验的两个数组?例如,y = [1,2,3,4,4,5,6]和x = [.1,.2,.5,.6,.7,.8,.9]; 我想要dy/dx!
gio*_*tto 23
使用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()
Run Code Online (Sandbox Code Playgroud)
eus*_*iro 16
使用numpy.diff
如果dx是常数
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.])
Run Code Online (Sandbox Code Playgroud)
dx不是常数(你的例子)
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.]
Run Code Online (Sandbox Code Playgroud)
请注意,这个近似的"衍生物"的大小n-1在哪里n是您的数组/列表大小.
不知道你想要实现什么,但这里有一些想法.
如果您正在尝试进行数值微分,那么有限差分公式可能会对您有所帮助.上述解决方案类似于具有非均匀网格/阵列的有限差分的正向模式的一阶精度近似.
我假设这是您的意思:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
也就是说,定义dx为中相邻元素之间的差异x。