温馨提示:本文翻译自stackoverflow.com,查看原文请点击:numpy - Calculating the derivative of points in python
numpy python scipy

numpy - 计算python中的点的导数

发布于 2020-03-28 23:41:23

我想计算点的导数,使用np.diff函数建议一些互联网帖子。但是,我尝试对手动计算的结果使用np.diff(选择一个随机多项式方程并对其进行微分),以查看是否得出相同的结果。我使用以下等式:Y =(X ^ 3)+(X ^ 2)+ 7,最终得到的结果是不同的。任何想法为什么?还有其他方法可以计算微分。

In the problem, I am trying to solve, I have recieved data points of fitted spline function ( not the original data that need to be fitted by spline but the points of the already fitted spline). The x-values are at equal intervals. I only have the points and no equation, what I require is to calculate, the first, second and third derivatives. i.e dy/dx, d2y/dx2, d3y/dx3. Any ideas on how to do this?. Thanks in advance.

xval = [1,2,3,4,5]
yval = []
yval_dashList = []

#selected a polynomial equation
def calc_Y(X):
      Y = (X**3) + (X**2) + 7
      return(Y)

#calculate y values using equatuion 
for i in xval:
    yval.append(calc_Y(i))

#output: yval = [9,19,43,87,157]

#manually differentiated the equation or use sympy library (sym.diff(x**3 + x**2 + 7))
def calc_diffY(X):
   yval_dash = 3*(X**2) + 2**X

#store differentiated y-values in a list
for i in xval:
    yval_dashList.append(yval_dash(i))

#output: yval_dashList = [5,16,35,64,107]

#use numpy diff method on the y values(yval)
numpyDiff = np.diff(yval)
#output: [10,24,44,60]

The values of numpy diff method [10,24,44,60] is different from yval_dashList = [5,16,35,64,107]

查看更多

查看更多

提问者
imantha
被浏览
182
lgsp 2020-01-31 17:59

The idea behind what you are trying to do is correct, but there are a couple of points to make it work as intended:

  1. There is a typo in calc_diffY(X), the derivative of X**2 is 2*X, not 2**X:
  def calc_diffY(X):    
      yval_dash = 3*(X**2) + 2*X

By doing this you don't obtain much better results:

yval_dash = [5, 16, 33, 56, 85]
numpyDiff = [10. 24. 44. 70.]
  1. 要计算数值导数,您应该做一个“微分商”,它是导数的近似值
numpyDiff = np.diff(yval)/np.diff(xval)

如果这些点的值更密集,则逼近会越来越好。x轴上的点之间的差为1,因此您最终会遇到这种情况(蓝色为解析导数,红色为数值):

在此处输入图片说明

如果将x点的差减小到0.1,则可以得到更好的效果:

在此处输入图片说明

只是为了添加一些内容,请看这张图片,该图片显示了减少从数值上衍生出导数的点的距离的效果,取自Wikipedia

在此处输入图片说明