In [1]:
from sympy import symbols, Function, Eq, Derivative, Rational, UnevaluatedExpr, solve
import xv.km
In [2]:
x, y, z, lamda = symbols('x, y, z, lamda')
k = symbols('k', constant = True)
f = Function('f')
F = Function('F')
g = Function('g')
In [3]:
eq1 = Eq(F(x, y, z, lamda), f(x, y, z) + lamda*(g(x, y, z) - k))
eq1
Out[3]:
In [4]:
F_x = Eq(Eq(Derivative(eq1.lhs, x), Derivative(eq1.rhs, x)), 0, evaluate = False)
F_x
Out[4]:
In [5]:
F_y = Eq(Eq(Derivative(eq1.lhs, y), Derivative(eq1.rhs, y)), 0, evaluate = False)
F_y
Out[5]:
In [6]:
F_z = Eq(Eq(Derivative(eq1.lhs, z), Derivative(eq1.rhs, z)), 0, evaluate = False)
F_z
Out[6]:
In [7]:
F_lamda = Eq(Eq(Derivative(eq1.lhs, lamda), Derivative(eq1.rhs, lamda)), 0, evaluate = False)
F_lamda
Out[7]:
Let x, y be real numbers. Find the maximum value of x + y, such that
In [8]:
eq2 = Eq(x**3 + y**3 + UnevaluatedExpr(x+y)/4 - Rational(15, 2), 0)
eq2
Out[8]:
In [9]:
eq3 = Eq(F(x, y, lamda), f(x, y) + lamda*(g(x, y) - k))
eq3
Out[9]:
In [10]:
f_eq = Eq(f(x, y), x + y)
f_eq
Out[10]:
In [11]:
g_eq = Eq(g(x, y), eq2.lhs)
g_eq
Out[11]:
In [12]:
eq4 = eq3.subs({f_eq.lhs: f_eq.rhs, g_eq.lhs: g_eq.rhs, k: 0})
eq4
Out[12]:
In [13]:
F_x = Eq(Derivative(eq4.rhs, x), 0, evaluate = False).doit()
F_x
Out[13]:
In [14]:
F_y = Eq(Derivative(eq4.rhs, y), 0, evaluate = False).doit()
F_y
Out[14]:
In [15]:
F_lamda = Eq(Derivative(eq4.rhs, lamda), 0, evaluate = False).doit()
F_lamda
Out[15]:
In [16]:
solns = solve((F_x, F_y, F_lamda), x, y, lamda, dict = True)
solns
Out[16]:
In [17]:
for sol in solns:
for var, val in sol.items():
display(Eq(var, val))
In [18]:
x_val = solve(F_x, x)[0]
x_val
Out[18]:
In [19]:
y_val = solve(F_y, y)[0]
y_val
Out[19]:
In [20]:
lamda_val = solve(F_lamda.subs({x: x_val, y: y_val}), lamda)[0]
lamda_val
Out[20]:
In [21]:
x_val.subs(lamda, lamda_val).simplify(force = True)
Out[21]:
In [22]:
y_val.subs(lamda, lamda_val).simplify(force = True)
Out[22]:
In [ ]:
In [ ]:
In [ ]:
In [23]:
def find_lagrange_multipliers(f_eq, g_eq, k = 0):
f_eq = Eq(f(x, y), f_eq)
g_eq = Eq(g(x, y), g_eq)
eq3 = Eq(F(x, y, lamda), f(x, y) + lamda*(g(x, y) - k))
eq4 = eq3.subs({f_eq.lhs: f_eq.rhs, g_eq.lhs: g_eq.rhs,})
F_x = Eq(Derivative(eq4.rhs, x), 0, evaluate = False).doit()
F_y = Eq(Derivative(eq4.rhs, y), 0, evaluate = False).doit()
F_lamda = Eq(Derivative(eq4.rhs, lamda), 0, evaluate = False).doit()
solns = solve((F_x, F_y, F_lamda), x, y, lamda, dict = True)
dict_solns = {x: [], y: []}
for sol in solns:
dict_solns[x].append(sol[x])
dict_solns[y].append(sol[y])
return dict_solns
In [24]:
f_eq = x + y
g_eq = x**3 + y**3 + UnevaluatedExpr(x+y)/4 - Rational(15, 2)
In [25]:
solns = find_lagrange_multipliers(f_eq, g_eq)
solns
Out[25]:
In [26]:
for i, j in solns.items():
print('The values of', i)
for val in j:
display(Eq(i, val, evaluate = False))
print('_'*50)
In [ ]: