#Exercices


#Exercise 1: Gradient of a Simple Function

#Task

  1. Define the function
  1. Compute the gradient of at ( x = 4 ).
Solution

The gradient (derivative) of is given by:

For ( x = 4 ):

#Code Template

import torch # Define the function f(x) = 3x^3 - 5x^2 + 2x def function(x): return 3 * x**3 - 5 * x**2 + 2 * x # Initialize the variable x = torch.tensor(4.0, requires_grad=True) # Compute the function value y = function(x) # Compute the gradient y.backward() # Print the gradient print(f'The gradient of the function at x = 4 is {x.grad.item()}')

#Exercise 2: Partial Derivatives of a Simple Multivariable Function

#Task

  1. Define the function :

  2. Compute the partial derivatives of and at the point .


Solution

1. Compute

The partial derivative of ( f ) with respect to ( x ) is:

Since

and

we get:

2. Compute

The partial derivative of ( f ) with respect to ( y ) is:

Since

and

we get:

At the point

we have:


#Code Template

import torch # Define the function f(x, y) = x^2 + 3xy + y^2 def function(x, y): return x**2 + 3 * x * y + y**2 # Initialize the variables x = torch.tensor(2.0, requires_grad=True) y = torch.tensor(3.0, requires_grad=True) # Compute the function value z = function(x, y) # Compute the partial derivatives z.backward() # Print the partial derivatives print(f'The partial derivative with respect to x at (2, 3) is {x.grad.item()}') print(f'The partial derivative with respect to y at (2, 3) is {y.grad.item()}')