首页
学习
活动
专区
圈层
工具
发布

Scipy导数
EN

Stack Overflow用户
提问于 2012-07-13 22:50:29
回答 1查看 9.1K关注 0票数 8

我有一个关于Scipy的导数函数的问题。我昨晚用了一下,得到了一些奇怪的答案。今天早上我用一些简单的函数再次尝试,得到了一些正确的答案和一些错误的答案。以下是我的测试:

代码语言:javascript
复制
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

我手动检查了poly3的值,-2 = 17,2= 95,0= 15。那么是我用错了函数,还是函数有问题。谢谢

使用:Python2.7.3,IPython 0.12.1,Numpy 1.6.1,Scipy 0.9.0,Linux Mint13

EN

回答 1

Stack Overflow用户

发布于 2012-07-13 22:57:03

正如derivative的文档所说:

代码语言:javascript
复制
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`.

您没有指定dx,所以它使用默认的1,它在这里太大了。例如:

代码语言:javascript
复制
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

或者,您可以增加订单:

代码语言:javascript
复制
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

求数值导数总是有点麻烦。

票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11472898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档