如何使用Python Pulp将主题限制为舍入整数

时间:2019-06-13 15:44:55

标签: python rounding pulp

我正在使用纸浆解决线性优化问题。我希望将主题四舍五入到100。应该怎么做。

我看到了答案,但是在这种情况下,我不知道如何定义整数变量I。 Use mod function in a constraint using Python Pulp

谢谢!

1 个答案:

答案 0 :(得分:2)

考虑一个简单的ILP,它由目标函数和变量约束组成:

min x1 + x2
s.t.
x1 + x2 >= 50
x1 >= 0 
x2 >= 0

要执行条件,您可以添加2个变量yz以及2个约束:

  1. y >= x1 + x2
  2. y == 100 * j for j >= 1

并在min y中更改目标函数。

在代码中:

原始配方

x1 = pulp.LpVariable('x1',lowBound=0,cat=pulp.LpContinuous)
x2 = pulp.LpVariable('x2',lowBound=0,cat=pulp.LpContinuous)

prob1 = pulp.LpProblem('example1',pulp.LpMinimize)
# obj
prob1+= 5*x1 + 10*x2
# constraints
prob1+= x1 + x2 >= 50

prob1.solve() 
print(pulp.value(prob1.objective)) #250

已转换

y = pulp.LpVariable('y',lowBound=0, cat=pulp.LpContinuous)
z = pulp.LpVariable('z',lowBound=1, cat=pulp.LpInteger)

prob2 = pulp.LpProblem('example2',pulp.LpMinimize)
# obj
prob2+= y
# constraints
prob2+= y >= 5*x1 + 10*x2
prob2+= y == 100 * z
prob2+= x1 + x2 >= 50

prob2.solve()
print(pulp.value(prob2.objective)) #300