Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scipy.misc.derivative for multiple argument function

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?

like image 621
tchakravarty Avatar asked Dec 20 '13 16:12

tchakravarty


People also ask

What is SciPy MISC?

misc) Various utilities that don't have another home. Note that the Python Imaging Library (PIL) is not a dependency of SciPy and therefore the pilutil module is not available on systems that don't have PIL installed.

How do I compute the derivative of an array in Python?

To compute the derivative of f_array , we use a NumPy function called gradient() . As we know from the limit definition of the derivative, we want “Change in x” to be as small as possible, so we get an accurate instantaneous rate of change for each point.

How do you differentiate a SymPy?

we can find the differentiation of mathematical expressions in the form of variables by using diff() function in SymPy package. To take multiple derivatives, pass the variable as many times as you wish to differentiate, or pass a number after the variable. It is also possible to call diff() method of an expression.

How do you find the partial derivative in Python?

Python Partial Derivative using SymPy Such derivatives are generally referred to as partial derivative. A partial derivative of a multivariable function is a derivative with respect to one variable with all other variables held constant. Let's partially differentiate the above derivatives in Python w.r.t x.


2 Answers

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
like image 153
alko Avatar answered Sep 30 '22 22:09

alko


Yes, it is implemented in sympy. Demo:

>>> from sympy import symbols, diff
>>> x, y = symbols('x y', real=True)
>>> diff( x**2 + y**3, y)
3*y**2
>>> diff( x**2 + y**3, y).subs({x:3, y:1})
3
like image 26
eseprimo Avatar answered Sep 30 '22 21:09

eseprimo