Search code examples
pythonpython-3.xmathgradient

How to find gradient of multiple variables at a given point?


I need to find gradient of function (x**2+y) at point [2, 4].

import numdifftools as nd
import sympy as sym
from sympy import *

x, y = sym.symbols('x y')

def rosen(x, y): 
    return (x**2 + y)
grad = nd.Gradient(rosen)([2, 4])
print("Gradient of is ", grad)
TypeError: rosen() missing 1 required positional argument: 'y'

Solution

  • Argument to function passed to nd.Gradient must be an array.

    import numdifftools as nd
    
    def rosen(xy): 
        return (xy[0]**2 + xy[1])
    
    grad = nd.Gradient(rosen)([2, 4])
    print("Gradient of is ", grad)