如何在 PuLP 中使用变量作为除数

How to use a variable as a divisor in PuLP

我试图解决 LP 问题,该问题的约束是通过将变量 A 除以变量 B 计算得出的。

问题的简单版本如下:

  1. The product is made by two materials (A and B)

  2. % of A should be greater than 50%

  3. % of B should be less than 40%

  4. Total amount of A and B are 100

Objective: What's the minimum amount of A?

代码如下:

from pulp import *

prob = LpProblem('Simple problem', LpMinimize)
x = LpVariable('x', 0, None, 'Integer')
y = LpVariable('y', 0, None, 'Integer')
prob += x
prob += x / (x + y) > 0.5  # <== Where the error happens
prob += y / (x + y) < 0.4
prob += x + y == 100
prob.solve()

print 'Result: %s' % LpStatus[prob.status]
print 'Amount of A: %s' % value(prob.objective)

但是我收到一条错误消息:

TypeError: Expressions cannot be divided by a non-constant expression

PuLP 似乎不支持变量作为除数。 https://github.com/coin-or/pulp/blob/master/src/pulp/pulp.py#L800

有什么想法吗?如果 PuLP 不是合适的库,我很乐意切换到任何适合的库。

2015 年 11 月 27 日更新

出于某种原因,上面的示例没有意义(未按预期工作)。我是这个图书馆的新手。也许根本不是解决我的问题的合适人选。因此,如果有人对其他图书馆有任何建议,我们将不胜感激。

顺便说一句,下面 Koen Peters 的建议很棒。采纳他的建议后,错误消失了。谢谢。

线性规划不理解除法,因此出现错误:) 你必须重新制定它,以便除法是线性制定的。 在这种情况下:

prob += x / (x + y) > 0.5  
prob += y / (x + y) < 0.4

相当于:

prob += x > 0.5 * (x + y)
prob += y < 0.4 * (x + y)

哪些是线性约束。 祝你好运!

我觉得在我的解决方案中不应该允许零——我包括了一个变量,它是 xy 的总和(认为你指的是 A).

from pulp import LpProblem, LpStatus, LpVariable
from pulp import LpMinimize, LpMaximize, lpSum, value

# I feel like zero shouldn't be allowed for lower bound...
x = LpVariable("x", lowBound=1, cat="Integer")
y = LpVariable("y", lowBound=1, cat="Integer")
z = LpVariable("z", lowBound=1, cat="Integer")

model = LpProblem("Divison problem", LpMinimize)

model += x
model += z == x + y
model += z == 100

# Rather than division, we can use multiplication
model += x >= z * 0.5
model += y <= z * 0.4

model.solve()

print(LpStatus[model.status])

print(f"""
x = {int(x.varValue):>3}  #  60
y = {int(y.varValue):>3}  #  40
z = {int(z.varValue):>3}  # 100
""")