numpy - 计算python中的点的导数

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

25
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)
``````