Skip to content
Related Articles

Related Articles

How to find Gradient of a Function using Python?

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Jul, 2020
View Discussion
Improve Article
Save Article

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[0])**2 +(x[1]-x[0]**2)**2

    where ‘rosen’ is name of function and ‘x’ is passed as array. x[0] and x[1] 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.

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.]
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!