scipy misc.derivative result is incorrect

python, scipy

Solution

`scipy.misc.derivative` is not exact. It uses a central difference formula to compute the derivative. The default spacing is `1.0`, which is pretty high for a lot of applications. Reducing it gives more accurate results:

>>> from scipy import misc
>>> def x3(x): return x*x*x
... 
>>> misc.derivative(x3, 1)
4.0
>>> misc.derivative(x3, 1, dx=0.5)
3.25
>>> misc.derivative(x3, 1, dx=0.25)
3.0625
>>> misc.derivative(x3, 1, dx=1.0/2**16)
3.0000000002328306

Problem

I'm wondering what I'm doing wrong here... I am experimenting with a simple and contrived function, taking it's derivative for certain values of x: `f(x) = x^3`, then evaluating the derivative `f'(x) = 3x^2` for values of x at 1, 2, 3 ``` >>> from scipy import misc >>> def x2(x): return x*x*x ... >>> misc.derivative(x2,1) 4.0 >>> misc.derivative(x2,2) 13.0 >>> misc.derivative(x2,3) 28.0 ``` problem: the results are incorrect, they are all +1 greater than they should be (they should be 3, 12 and 27 respectively).

Original source