Output of numpy.diff is wrong

2019-09-07 01:06发布

问题:

here's my problem: I am trying to use numpy to compute (numerical) derivatives, but I am finding some problems in the value the function numpy.diff returns (and numpy.gradient as well). What I find is that the values are totally wrong! here's a code sample:

import numpy as np
x = np.linspace(-5, 5, 1000)
y = x**2
yDiff = np.diff(y)
print y[0], yDiff[0]

The output of this script is:

25.0 -0.0999998997997

where the first value is right, the second is exactly 100 times smaller than the one it should be (considering approximations)! I have made different attempts and this is not a problem related to the boundaries of the function, and this 100 factor seems systematic... Can this be related to some normalization np.diff is doing? Or perhaps I am just missing something important without noticing? Thanks for the help

回答1:

np.diff doesn't calculate the derivative it just calulates finite differences; you have to account for the spacing yourself. Try

np.diff(y) / (x[1] - x[0])

Btw., np.linspace has a retstep keyword that is convenient in this context:

x, dx = np.linspace(-5, 5, 100, retstep=True)
...
np.diff(y) / dx