ILP 基礎與 PuLP 入門
整數線性規劃 (Integer Linear Programming) 是數學最佳化中最重要的方法之一。它的核心是:用線性方程式描述問題,並要求部分或全部變數為整數。
目標: 最大化/最小化 c₁x₁ + c₂x₂ + ... + cₙxₙ
限制:
a₁₁x₁ + a₁₂x₂ + ... + a₁ₙxₙ ≤ b₁
a₂₁x₁ + a₂₂x₂ + ... + a₂ₙxₙ ≤ b₂
...
x₁, x₂, ..., xₙ ≥ 0
部分 xᵢ 為整數
安裝 PuLP
pip install pulp
第一個 ILP 模型:生產規劃
import pulp
# 建立問題(最大化利潤)
prob = pulp.LpProblem("生產規劃", pulp.LpMaximize)
# 決策變數:每個產品的生產數量
x1 = pulp.LpVariable("產品A", lowBound=0, cat="Integer")
x2 = pulp.LpVariable("產品B", lowBound=0, cat="Integer")
# 目標函數:最大化利潤
prob += 40 * x1 + 30 * x2, "總利潤"
# 限制條件
prob += 2 * x1 + 1 * x2 <= 100, "原料限制"
prob += 1 * x1 + 2 * x2 <= 80, "工時限制"
prob += x1 <= 40, "產品A市場需求"
# 求解
prob.solve()
print(f"求解狀態: {pulp.LpStatus[prob.status]}")
print(f"產品A 生產: {int(x1.value())} 單位")
print(f"產品B 生產: {int(x2.value())} 單位")
print(f"總利潤: {pulp.value(prob.objective)}")