Related Articles

# How to find Gradient of a Function using Python?

• Last Updated : 28 Jul, 2020

The gradient of a function simply means the rate of change of a function. We will use numdifftools to find Gradient of a function.

Examples:

```Input : x^4+x+1
Output :Gradient of x^4+x+1 at x=1 is  4.99

Input :(1-x)^2+(y-x^2)^2
Output :Gradient of (1-x^2)+(y-x^2)^2 at (1, 2) is  [-4.  2.]
```

Approach:

• For Single variable function: For single variable function we can define directly using “lambda” as stated below:-
`g=lambda x:(x**4)+x+1`
• For Multi-Variable Function: We will define a function using “def” and pass an array “x” and it will return multivariate function as described below:-
```def rosen(x):
return (1-x)**2 +(x-x**2)**2```

where ‘rosen’ is name of function and ‘x’ is passed as array. `x` and `x` are array elements in the same order as defined in array.i.e Function defined above is `(1-x^2)+(y-x^2)^2`.

Similarly, We can define function of more than 2-variables also in same manner as stated above.

Syntax:

`nd.Gradient(func_name)`

Example:

 `import` `numdifftools as nd`` ` ` ` `g ``=` `lambda` `x:(x``*``*``4``)``+``x ``+` `1``grad1 ``=` `nd.Gradient(g)([``1``])``print``(``"Gradient of x ^ 4 + x+1 at x = 1 is "``, grad1)`` ` `def` `rosen(x): ``    ``return` `(``1``-``x[``0``])``*``*``2` `+``(x[``1``]``-``x[``0``]``*``*``2``)``*``*``2`` ` `grad2 ``=` `nd.Gradient(rosen)([``1``, ``2``])``print``(``"Gradient of (1-x ^ 2)+(y-x ^ 2)^2 at (1, 2) is "``, grad2)`

Output:

```Gradient of x^4+x+1 at x=1 is  4.999999999999998
Gradient of (1-x^2)+(y-x^2)^2 at (1, 2) is  [-4.  2.]```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up