0

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

mmonti
  • 93
  • 2
  • 13

1 Answers1

4

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
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • Oh s**t you're right! I just assumed that finite difference just meant numerical derivative. And I didn't read carefully enough the examples apparently, now everything makes more sense. – mmonti Mar 11 '17 at 16:43
  • @mmonti It would be quite difficult for `np.diff` to calculate the derivative since nobody is telling it the x spacing ;-) – Paul Panzer Mar 11 '17 at 16:46
  • Actually that was puzzling me at the beginning, but I just passed over... Anyway thank you. – mmonti Mar 11 '17 at 16:50