Reputation: 3474
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).
Upvotes: 3
Views: 2252
Reputation: 2500
If you specify dx
or the spacing to a small enough number you'll get a decent approximation.
>>> from scipy import misc
>>> def f(x): return x*x*x
...
>>> misc.derivative(f,2,dx=0.1)
12.010000000000009
>>> round(misc.derivative(f,2,dx=0.1),0)
12.0
Upvotes: 1
Reputation: 280291
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
Upvotes: 6