多参数函数的scipy.misc.derivative [英] scipy.misc.derivative for multiple argument function

查看:533
本文介绍了多参数函数的scipy.misc.derivative的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用SciPy函数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, ))

但是相对于第二个参数,我将如何使用函数foo的派生呢?我能想到的一种方法是生成一个lambda函数,该函数可以调整周围的参数,但是很快就会变得麻烦.

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)

演示:

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

这篇关于多参数函数的scipy.misc.derivative的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆