Implementing Partial Derivatives in Python
Desliza para mostrar el menú
In this video, you will learn how to compute partial derivatives of multivariable functions using Python. They are essential in optimization, machine learning, and data science for analyzing how a function changes with respect to one variable while keeping others constant.
1. Defining a Multivariable Function
x, y = sp.symbols('x y')
f = 4*x**3*y + 5*y**2
- Here, we define x and y as symbolic variables;
- We then define the function f(x,y)=4x3y+5y2.
2. Computing Partial Derivatives
df_dx = sp.diff(f, x)
df_dy = sp.diff(f, y)
sp.diff(f, x)computes ∂x∂f while treating y as a constant;sp.diff(f, y)computes ∂y∂f while treating x as a constant.
3. Evaluating Partial Derivatives at (x=1, y=2)
df_dx_val = df_dx.subs({x: 1, y: 2})
df_dy_val = df_dy.subs({x: 1, y: 2})
- The
.subs({x: 1, y: 2})function substitutes x=1 and $$y=2$4 into the computed derivatives; - This allows us to numerically evaluate the derivatives at a specific point.
4. Printing the Results
We print the original function, its partial derivatives, and their evaluations at (1,2).
12345678910111213141516import sympy as sp x, y = sp.symbols('x y') f = 4*x**3*y + 5*y**2 df_dx = sp.diff(f, x) df_dy = sp.diff(f, y) df_dx_val = df_dx.subs({x: 1, y: 2}) df_dy_val = df_dy.subs({x: 1, y: 2}) print("Function: f(x, y) =", f) print("∂f/∂x =", df_dx) print("∂f/∂y =", df_dy) print("∂f/∂x at (1,2) =", df_dx_val) print("∂f/∂y at (1,2) =", df_dy_val)
¿Todo estuvo claro?
¡Gracias por tus comentarios!
Sección 1. Capítulo 24
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Sección 1. Capítulo 24