Nhập môn Tối ưu hóa với Python
Jasmin Ludolf
Content Developer
Hàm mục tiêu và ràng buộc có quan hệ tuyến tính
Trái với "tuyến tính có ràng buộc": pha trộn tuyến tính/phi tuyến
| Loại | Số lượng | Chai (giờ/thùng) | Cốc (giờ/thùng) |
|---|---|---|---|
| $M_A$ | 4 | 1.5 | 1.3 |
| $M_B$ | 3 | 0.8 | 2.1 |
| B ($/thùng) | C ($/thùng) |
|---|---|
| 480 | 510 |
from pulp import *model = LpProblem('MaxProfit', LpMaximize)B = LpVariable('B', lowBound=0) C = LpVariable('C', lowBound=0)model += 480*B + 510*Cmodel += 1.5*B + 1.3*C - 120, "M_A" model += 0.8*B + 2.1*C - 90, "M_B"
LpMaximize hoặc LpMinimizeprint(model)
ProductMix:
TỐI ĐA HÓA
480*B + 510*C + 0
RÀNG BUỘC
M_A: 1.5 B + 1.3 C <= 120
M_B: 0.8 B + 2.1 C <= 90
BIẾN
B Liên tục
C Liên tục
status = model.solve()
print(status)
Welcome to the CBC MILP Solver
...
1
print(f"Profit = {value(model.objective):.2f}")
print(f"Tons of bottles = {B.varValue:.2f}, tons of cups = {C.varValue:.2f}")
Lợi nhuận = 40137.44
Thùng chai = 63.98, thùng cốc = 18.48
variables = LpVariable.dicts("Product", ['B', 'C'], lowBound=0)
OR
variables = LpVariable.dicts("Product", range(2), 0)
A = LpVariable.matrix('A', (range(2), range(2)), 0)
box_profit = {'B': 480, 'C': 510}
model += lpSum([box_profit[i] * variables[i] for i in ['B', 'C']])
model += 1.5*variables['B'] + 1.3*variables['C'] <= 120, "M_A"
model += 0.8*variables['B'] + 2.1*variables['C'] <= 90, "M_B"
Nhập môn Tối ưu hóa với Python