Open In App

How to find Gradient of a Function using Python?

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:

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



Method used: Gradient()
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.]
Article Tags :