scipy.misc.derivative for multiple argument function

后端 未结 3 1749
清酒与你
清酒与你 2020-12-28 18:39

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

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-28 19:34

    Here is an answer for numerical differentiation using numdifftools.

    import numpy as np
    import numdifftools as nd
    
    def partial_function(f___,input,pos,value):
        tmp  = input[pos]
        input[pos] = value
        ret = f___(*input)
        input[pos] = tmp
        return ret
    
    def partial_derivative(f,input):
        ret = np.empty(len(input))
        for i in range(len(input)):
            fg = lambda x:partial_function(f,input,i,x)
            ret[i] = nd.Derivative(fg)(input[i])
        return ret
    

    Then:

    print (partial_derivative(lambda x,y: x*x*x+y*y,np.array([1.0,1.0])))
    

    Gives:

    [ 3.  2.]
    

提交回复
热议问题