【发布时间】:2019-02-05 07:24:26
【问题描述】:
我正在尝试重现这种混合 example 但使用较少的变量,这部分工作得很好:
import pulp
from pulp import *
# Creates a list of the Ingredients
Ingredients = ['CHICKEN', 'BEEF', 'MUTTON', 'RICE']
# A dictionary of the costs of each of the Ingredients is created
costs = {'CHICKEN': 15,
'BEEF': 12,
'MUTTON': 17,
'RICE': 12
}
# A dictionary of the protein percent in each of the Ingredients is created
proteinPercent = {'CHICKEN': 17,
'BEEF': 2,
'MUTTON': 16,
'RICE': 8
}
# A dictionary of the fat percent in each of the Ingredients is created
fatPercent = {'CHICKEN': 10,
'BEEF': 14,
'MUTTON': 13,
'RICE': 16,
}
# Create the 'prob' variable to contain the problem data
prob = LpProblem("The Whiskas Problem", LpMinimize)
# A dictionary called 'ingredient_vars' is created to contain the referenced Variables
ingredient_vars = LpVariable.dicts("Ingr",Ingredients,0)
# The objective function is added to 'prob' first
prob += lpSum([costs[i]*ingredient_vars[i] for i in Ingredients]), "Total Cost of Ingredients per can"
# The constraints are added to 'prob'
prob += lpSum([proteinPercent[i] * ingredient_vars[i] for i in Ingredients]) >= 15.5, "ProteinRequirement"
prob += lpSum([fatPercent[i] * ingredient_vars[i] for i in Ingredients]) >= 12.3, "FatRequirement"
prob.writeLP("WhiskasModel.lp")
prob.solve()
# The status of the solution is printed to the screen
print ("Status:", LpStatus[prob.status])
# Each of the variables is printed with it's resolved optimum value
for v in prob.variables():
print (v.name, "=", v.varValue)
# The optimised objective function value is printed to the screen
print ("Total Cost of Ingredients per can = ", value(prob.objective))
它计算每种成分所需的最佳量:
Status: Optimal
Ingr_BEEF = 0.0
Ingr_CHICKEN = 0.77916667
Ingr_MUTTON = 0.0
Ingr_RICE = 0.28177083
Total Cost of Ingredients per can = 15.068750009999999
但是当我将约束添加到代码中时,这并不等于 100%:
prob += lpSum([ingredient_vars[i] for i in Ingredients]) == 100, "PercentagesSum"
我得到这个结果:
Status: Optimal
Ingr_BEEF = 100.0
Ingr_CHICKEN = 0.0
Ingr_MUTTON = 0.0
Ingr_RICE = 0.0
Total Cost of Ingredients per can = 1200.0
这是错误的,因为它不满足其他约束。
编辑
看来我解释错了,我在想: 如果我想生产 3 个单位,输入的总和应该是 3。
我认为是这样的:
# The constraints are added to 'prob'
prob += lpSum([ingredient_vars[i] for i in Ingredients]) == 3, "PercentagesSum"
prob += lpSum(ingredient_vars["CHICKEN"]) <= 2, "CHICKEN"
prob += lpSum(ingredient_vars["BEEF"]) <= 1, "BEEF"
prob += lpSum(ingredient_vars["MUTTON"]) <= 1, "MUTTON"
prob += lpSum(ingredient_vars["RICE"]) <= 1, "RICE"
其中 2,1,1,1 是每种原材料的可用数量。
【问题讨论】:
-
prob += lpSum([ingredient_vars[i] for i in Ingredients]) == 100应该是prob += lpSum([ingredient_vars[i] for i in Ingredients]) == 1.0 -
是的,这正是我想要的。
标签: python optimization linear-programming pulp