Saturday, November 22, 2025
HomeLanguagesHow to find Gradient of a Function using Python?

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:

  • 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.]
RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6850 POSTS0 COMMENTS