Home > Blockchain >  Useage of scipy
Useage of scipy

Time:01-15

from scipy.misc import derivative
def fun(x):
    return x**3   x**2

derivative(fun,1)

The answer comes out to be 6 but it should be 5. Am I doing something wrong?

In the official documentation it says to use dx=1e-6 . Why should I use this here ? And what is the use of dx?

CodePudding user response:

By looking at the code ([source] on the doc page), and a bit of experimentation, I found that:

In [472]: derivative(fun,1)
Out[472]: 6.0
In [473]: derivative(fun,1,1)
Out[473]: 6.0
In [474]: dx=1;(fun(1 dx)-fun(1-dx))/(2*dx)
Out[474]: 6.0
In [475]: derivative(fun,1,.5)
Out[475]: 5.25
In [476]: dx=.5;(fun(1 dx)-fun(1-dx))/(2*dx)
Out[476]: 5.25
In [477]: derivative(fun,1,.1)
Out[477]: 5.010000000000001
In [478]: dx=.1;(fun(1 dx)-fun(1-dx))/(2*dx)
Out[478]: 5.010000000000001

With the default n and order it estimates the derivative from 2 points, one on each side of the x0. The smaller the dx the better you will capture the slope at a x0, with the caution about rounding errors if it's too small.

  •  Tags:  
  • Related