本文主要是介绍Gurobi求解目标函数最优值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
"""
求解目标函数最大值
x+y+2*z
约束条件
x+2*y+3*z<=4
x+y>=1"""from gurobipy import *
try:m = Model("mip1")x = m.addVar(vtype=GRB.BINARY,name="x")y = m.addVar(vtype=GRB.BINARY,name="y")z = m.addVar(vtype=GRB.BINARY,name="z")m.setObjective(x+y+2*z,GRB.MAXIMIZE)m.addConstr(x+2*y+3*z<=4,"c0")m.addConstr(x+y>=1,"c1")m.optimize()#打印变量名称和变量值for v in m.getVars():print(v.varName,v.x)print( m.objVal)
#捕捉程序运行中的错误
except GurobiError as e:print("Erroe code" + str(e.errno) + ":" + str(e))except AttributeError:print("Encountered an attribute erroe")
from gurobipy import *#所需营养
categories,minNutrition,maxNutrition = multidict({"calories":[1800,2200],"protein":[91,GRB.INFINITY],"fat":[0,65],"sodium":[0,1779]})
#食物已经对应的cost
foods,cost = multidict({"hamburger":2.49,"chicken":2.89,"hot dog":1.50,"fries":1.89,"macaroni":2.09,"pizza":1.99,"salad":2.49,"milk":0.89,"ice cream":1.59})#每种食物所对应的营养价值
nutritionValues = {("hamburger","calories"):410,("hamburger","protein"):24,("hamburger","fat"):26,("hamburger","sodium"):420,("chicken","calories"):420,("chicken","protein"):32,("chicken","fat"):10,("chicken","sodium"):1190,("hot dog","calories"):380,("hot dog","protein"):4,("hot dog","fat"):19,("hot dog","sodium"):1800,("fries", "calories"):380,("fries", "protein"):4,("fries", "fat"):19,("fries", "sodium"):270,("macaroni", "calories"):320,("macaroni", "protein"):12,("macaroni", "fat"):10,("macaroni", "sodium"):930,("pizza", "calories"):320,("pizza", "protein"):15,("pizza", "fat"):12,("pizza", "sodium"):820,("salad", "calories"):320,("salad", "protein"):31,("salad", "fat"):12,("salad", "sodium"):1230,("milk", "calories"):100,("milk", "protein"):8,("milk", "fat"):2.5,("milk", "sodium"):125,("ice cream", "calories"):330,("ice cream", "protein"):8,("ice cream", "fat"):10,("ice cream", "sodium"):180,}#创建模型
m = Model("diet")#添加变量
buy = m.addVars(foods,name="buy")#构建目标函数
m.setObjective(buy.prod(cost),GRB.MINIMIZE)#添加约束条件m.addConstrs((quicksum(nutritionValues[f,c]*buy[f] for f in foods)==[minNutrition[c],maxNutrition[c]]for c in categories),"_")def printSolution():if m.status == GRB.Status.OPTIMAL:print("\nCost: %g" % m.objVal)print("\nBuy:")buyx = m.getAttr("x",buy)for f in foods:if buy[f].x > 0.0001:print("%s %g" % (f, buyx[f]))else:print("No solution")
m.optimize()
printSolution()
这篇关于Gurobi求解目标函数最优值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!