Introduction to Optimization in Python
Jasmin Ludolf
Content Developer
Utility function:
import numpy as np import matplotlib.pyplot as plt
w = np.linspace(1, 30, 100) l = np.linspace(1, 30, 100)
W, L = np.meshgrid(w, l)
F = W**0.4 * L**0.6
plt.figure(figsize=(8, 6))
contours = plt.contour(W, L, F, levels=[5, 10, 15, 20])
plt.clabel(contours)
plt.title('Indifference Curves for the function: w**0.4 * l**0.6') plt.xlabel('w') plt.ylabel('l') plt.grid(True) plt.show()
$$ \max_{w,l} w^{0.4}l^{0.6}$$ $$s.t.\ \ \ w+l = 24$$
l = 24 - w
plt.plot(w, l, color='red')
def utility_function(vars): w, l = vars return -(w**0.4 * l**0.6)
def constraint(vars): return 24 - np.sum(vars)
initial_guess = [12, 12] constraint_definition = {'type': 'eq', 'fun': constraint} result = minimize(utility_function, initial_guess, constraints=constraint_definition) print(result.x)
[ 9.60001122 14.39998878]
Introduction to Optimization in Python