# lagrange-example.ipynb

In [81]:
from sympy import symbols, Symbol, Eq, Derivative, solve, Function, Rational, UnevaluatedExpr
from sympy.vector import Del

In [82]:
h = symbols('h') # labor in hours
s = symbols('s') # steel in tons
lamda = symbols('lamda') # steel in tons
R = Function('R')(h, s) #revenue
g = Function('g')(h, s) #constraint

Del_R = Symbol(r'\nabla R')
Del_g = Symbol(r'\nabla g')

In [83]:
R_eq = Eq(R, 100*h**Rational(2, 3)*s**Rational(1, 3))
R_eq

Out[83]:
$\displaystyle R{\left(h,s \right)} = 100 h^{\frac{2}{3}} \sqrt[3]{s}$
In [84]:
B = 20000

In [85]:
g_eq = Eq(Eq(g, 20*h + 2000*s), B, evaluate = False)
g_eq

Out[85]:
$\displaystyle g{\left(h,s \right)} = 20 h + 2000 s = 20000$
In [89]:
Lm_eq = Eq(Del_R, lamda*UnevaluatedExpr(Del_g))
Lm_eq

Out[89]:
$\displaystyle \nabla R = \lambda \nabla g$
In [92]:
diff_R_eq_h = Eq(Derivative(R, h), Derivative(100*h**Rational(2, 3)*s**Rational(1, 3), h)).doit()
diff_R_eq_h

Out[92]:
$\displaystyle \frac{\partial}{\partial h} R{\left(h,s \right)} = \frac{200 \sqrt[3]{s}}{3 \sqrt[3]{h}}$
In [93]:
diff_R_eq_s = Eq(Derivative(R, s), Derivative(100*h**Rational(2, 3)*s**Rational(1, 3), s)).doit()
diff_R_eq_s

Out[93]:
$\displaystyle \frac{\partial}{\partial s} R{\left(h,s \right)} = \frac{100 h^{\frac{2}{3}}}{3 s^{\frac{2}{3}}}$
In [94]:
diff_g_eq_h = Eq(Derivative(g, h), Derivative(20*h + 2000*s, h)).doit()
diff_g_eq_h

Out[94]:
$\displaystyle \frac{\partial}{\partial h} g{\left(h,s \right)} = 20$
In [95]:
diff_g_eq_s = Eq(Derivative(g, s), Derivative(20*h + 2000*s, s)).doit()
diff_g_eq_s

Out[95]:
$\displaystyle \frac{\partial}{\partial s} g{\left(h,s \right)} = 2000$
In [99]:
diff_lm_h = Eq(Derivative(100*h**Rational(2, 3)*s**Rational(1, 3), h), lamda*Derivative(20*h + 2000*s, h)).doit()
diff_lm_h

Out[99]:
$\displaystyle \frac{200 \sqrt[3]{s}}{3 \sqrt[3]{h}} = 20 \lambda$
In [100]:
diff_lm_s = Eq(Derivative(100*h**Rational(2, 3)*s**Rational(1, 3), s), lamda*Derivative(20*h + 2000*s, s)).doit()
diff_lm_s

Out[100]:
$\displaystyle \frac{100 h^{\frac{2}{3}}}{3 s^{\frac{2}{3}}} = 2000 \lambda$
In [103]:
budget_eq = Eq(20*h + 2000*s, B)
budget_eq

Out[103]:
$\displaystyle 20 h + 2000 s = 20000$
In [108]:
solns = solve([diff_lm_h, diff_lm_s, budget_eq], [h, s, lamda], dict = True)[0]

In [113]:
R_eq.subs(solns).n()

Out[113]:
$\displaystyle R{\left(\frac{2000}{3},\frac{10}{3} \right)} = 11399.8396445113$
In [ ]: