17. SciPy求函数的导数
在SciPy里提供了很多的方法函数可以实现对某函数进行求导和求积分的操作。
SciPy的求导相对简单也容易理解。已知函数$f(x)$求其在$x_0$的导数即$f'(x_0)$。
方法一,使用scipy.misc模块下的derivative方法函数。
import numpy as np
from scipy.misc import derivative
def f(x):
return x**5
for x in range(1, 4):
print derivative(f, x, dx=1e-6)
程序的执行结果:
4.999999999866223
80.00000000230045
405.00000005749826
这里的$f(x)= x^5$那么$f'(x) = 5 x^4$,当$x= 1$时$f'(x = 1) = 5$,当$x = 2$时$f'(x = 2) = 5\times 2 ^ 4 = 80$ 。
derivative方法函数还可以指定导数的阶数,下面求一下二阶导数。
import numpy as np
from scipy.misc import derivative
def f(x):
return x**5
for x in range(1, 4):
print derivative(f, x, dx=1e-6, n = 2)
程序的执行结果:
19.999335520992645
160.02132952053216
540.0124791776761
这里的$f(x)=