简体   繁体   English

Scipy Derivative

[英]Scipy Derivative

I have a question about the derivative function of Scipy. 我对Scipy的衍生功能有疑问。 I used it last night and got some odd answers. 我昨晚用它并得到了一些奇怪的答案。 I tried again this morning with some simple functions and got some right answers and some wrong. 我今天早上再次尝试了一些简单的功能,得到了一些正确的答案和一些错误。 Here were my tests: 这是我的测试:

In [1]: def poly1(x):
...:     return x**2

In [3]: derivative(poly1, 0)
Out[3]: 0.0

In [4]: def poly2(x):
...:    return (x-3)**2

In [6]: derivative(poly2, 3)
Out[6]: 0.0

In [8]: def sin1(x):
...:     return sin(x)

In [14]: derivative(sin1, pi/2)
Out[14]: 5.5511151231257827e-17

In [15]: def poly3(x):
....:     return 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2

In [19]: derivative(poly3, -2)
Out[19]: -39.0

In [20]: derivative(poly3, 2)
Out[20]: 121.0

In [22]: derivative(poly3, 0)
Out[22]: 17.0

I checked the values of poly3 by hand and -2 = 17, 2 = 95, 0 = 15. So am I using the function wrong, or is there something wrong with the function. 我用手检查了poly3的值,并且-2 = 17,2 = 95,0 = 15.所以我使用的函数是错误的,或者函数是否有问题。 Thanks 谢谢

Using: Python 2.7.3, IPython 0.12.1, Numpy 1.6.1, Scipy 0.9.0, Linux Mint 13 使用:Python 2.7.3,IPython 0.12.1,Numpy 1.6.1,Scipy 0.9.0,Linux Mint 13

As the documentation for derivative says: 正如derivative文件所说:

derivative(func, x0, dx=1.0, n=1, args=(), order=3)
    Find the n-th derivative of a function at point x0.

    Given a function, use a central difference formula with spacing `dx` to
    compute the n-th derivative at `x0`.

You didn't specify dx , so it used the default of 1 , which is too large here. 您没有指定dx ,因此它使用默认值1 ,这在这里太大了。 For example: 例如:

In [1]: from scipy.misc import derivative

In [2]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=1)
Out[2]: -39.0

In [3]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=0.5)
Out[3]: -22.5

In [4]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=0.1)
Out[4]: -17.220000000000084

In [5]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=0.01)
Out[5]: -17.0022000000003

In [6]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=1e-5)
Out[6]: -17.000000001843318

Alternatively, you could increase the order: 或者,您可以增加订单:

In [7]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=1, order=5)
Out[7]: -17.0

Taking numerical derivatives is always a little troublesome. 采用数值导数总是有点麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM