Introduction to Optimization in Python
Jasmin Ludolf
Content Developer
$$ w\leq 5$$
Objective:
Bounds
$$\max_{q_A,q_B}R(q_A,q_B)-C(q_A,q_B)$$
$$s.t.$$
$$R(q_A,q_B)=\left[120-(q_A+q_B)\right](q_A+q_B)$$
$$\ \ \ \ \ C(q_A,q_B)=3q_A+3.5q_B$$
$$\ \ \ 0\leq q_A, q_B\leq 90$$
$$ \ \ \ \ 92\leq q_A+q_B$$
from scipy.optimize import minimize,\ Bounds, LinearConstraint
def R(q): return (120 - (q[0] + q[1] )) * (q[0] + q[1])
def C(q): return 3*q[0] + 3.5*q[1]
def profit(q): return R(q) - C(q)
bounds = Bounds([0, 0], [90, 90])
constraints = LinearConstraint([1, 1], lb=92)
result = minimize(lambda q: -profit(q),
[50, 50],
bounds=bounds, constraints=constraints)
print(result.message) print(f'The optimal number of cars produced in plant A is: {result.x[0]:.2f}') print(f'The optimal number of cars produced in plant B is: {result.x[1]:.2f}') print(f'The firm made: ${-result.fun:.2f}')
Optimization terminated successfully
The optimal number of cars produced in plant A is: 90.00
The optimal number of cars produced in plant B is: 2.00
The firm made: $2299.00
from scipy.optimize import NonlinearConstraint import numpy as np
constraints = NonlinearConstraint(lambda q: q[0] + q[1], lb=92, ub=np.Inf)
result = minimize(lambda q: -profit(q), [50, 50], bounds=Bounds([0, 0], [90, 90]), constraints=constraints)
print(result.message)
print(f'The optimal number of cars produced in plant A is: {result.x[0]:.2f}')
print(f'The optimal number of cars produced in plant B is: {result.x[1]:.2f}')
print(f'The firm made: ${-result.fun:.2f}')
Optimization terminated successfully
The optimal number of cars produced in plant A is: 90.00
The optimal number of cars produced in plant B is: 2.00
The firm made: $2299.00
LinearConstraint()
for straightforward, linear problemsNonlinearConstraint()
Introduction to Optimization in Python