python scipy.misc derivative_多参数函数的scipy.misc.derivative

It is straightforward to compute the partial derivatives of a function at a point with respect to the first argument using the SciPy function scipy.misc.derivative. Here is an example:

def foo(x, y):

return(x**2 + y**3)

from scipy.misc import derivative

derivative(foo, 1, dx = 1e-6, args = (3, ))

But how would I go about taking the derivative of the function foo with respect to the second argument? One way I can think of is to generate a lambda function that rejigs the arguments around, but that can quickly get cumbersome.

Also, is there a way to generate an array of partial derivatives with respect to some or all of the arguments of a function?

解决方案

I would write a simple wrapper, something along the lines of

def partial_derivative(func, var=0, point=[]):

args = point[:]

def wraps(x):

args[var] = x

return func(*args)

return derivative(wraps, point[var], dx = 1e-6)

Demo:

>>> partial_derivative(foo, 0, [3,1])

6.0000000008386678

>>> partial_derivative(foo, 1, [3,1])

2.9999999995311555

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值