参考:Python求解线性规划——PuLP使用教程 - Only(AR) - 博客园 (cnblogs.com)
1.Define the model
model = pl.LpProblem(name="",sense=pl.LpMaximize)
name 模型的名字
sense 模型的类型(pl.LpMaximize/pl.LpMinimize)
2.Define the decision variables
用x[i]存储变量,命名为xi
x = {i: pl.LpVariable(name=f"x{i}", lowBound=,upBound=, cat=) for i in range(1,)}
name 变量名
lowBound 变量最小值(默认负无穷)
upBound 变量最大值 (默认正无穷)
cat 变量的类型(pl.Binary 0/1,pl.Integer 整数,pl.Continuous 实数(默认值))
3.Set the objective
目标函数不用括号
model += x[1]+x[2]+x[3]
4.Add constraints
约束式用括号括起来
式子可以是>=,<=,==,不能是>,<,=
model += (2*x[1]+3*x[2]+x[3]>=10)
5.Solve the optimization problem
status = model.solve()
6.Print the results
print(f"status: {pl.LpStatus[model.status]}")
print(f"objective: {model.objective.value()}")
for var in model.variables():
print(f"{var.name}: {var.value()}")
for name, constraint in model.constraints.items():
print(f"{name}: {constraint.value()}")
pl.LpStatus[model.status] | 解释 |
---|---|
Optimal | 找到了最优解 |
Not Solved | 问题尚未被求解 |
Infeasible | 问题是不可行的,即不存在满足所有约束条件的解 |
Unbounded | 问题是无界的,即目标函数可以无限增加(或无限减少)而不受限制 |
Undefined | 问题是未定义的,通常表示输入数据错误或问题规格不正确 |
*完整代码
《数学建模算法与应用》司守奎、孙兆亮 例1.2
import pulp as pl
model = pl.LpProblem(name="problem",sense=pl.LpMaximize)
x = {i:pl.LpVariable(name=f"x{i}",lowBound=0,cat=pl.LpContinuous) for i in range(1,4)}
model += (2 * x[1] - 5 * x[2] + x[3] >= 10)
model += (x[1] + 3 * x[2] + x[3] <= 12)
model += (x[1] + x[2] + x[3] == 7)
model += 2 * x[1] + 3 * x[2] -5 * x[3]
status = model.solve()
print(f"status:{pl.LpStatus[model.status]}")
print(f"objective:{model.objective.value()}")
for var in model.variables():
print(f"{var.name}:{var.value()}")
for name,constraint in model.constraints.items():
print(f"{name}:{constraint.value()}")
标签:status,name,Python,print,lowBound,库解,model,pulp,pl
From: https://www.cnblogs.com/cyxcc/p/17966333