gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:29:02 25 4
gpt4 key购买 nike

我试图通过将变量 A 除以变量 B 来计算约束来解决 LP 问题。

问题的简单版本如下:

  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)

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

关于python - 如何在 PuLP 中使用变量作为除数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33929353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com