@[toc]
问题
代码
import gurobi.*;
/**
* @Author:WSKH
* @ClassName:TestGurobi
* @ClassType:
* @Description:
* @Date:2022/6/5/11:38
* @Email:1187560563@qq.com
* @Blog:https://blog.csdn.net/weixin_51545953?type=blog
*/
public class TestGurobi{
public static void main(String[] args) {
try {
// 创建环境
GRBEnv grbEnv = new GRBEnv("grbEnv");
// 创建模型
GRBModel grbModel = new GRBModel(grbEnv);
// 声明CONTINUOUS连续变量
GRBVar x1 = grbModel.addVar(-10, 50, -10, GRB.CONTINUOUS, "x1");
GRBVar x2 = grbModel.addVar(0, Double.MAX_VALUE, 0, GRB.CONTINUOUS, "x2");
GRBVar x3 = grbModel.addVar(5, 5, 5, GRB.CONTINUOUS, "x3");
// 声明变量数组
GRBVar[] grbVars = {x1, x2, x3};
// 声明约束
// 约束1:x1+2*x2+x3<=100
GRBLinExpr expr1 = new GRBLinExpr();
expr1.addTerms(new double[]{1,2,1},grbVars);
grbModel.addConstr(expr1,GRB.LESS_EQUAL,100,"expr1");
// 约束2:x1+x2-2x3>=10
GRBLinExpr expr2 = new GRBLinExpr();
expr2.addTerms(new double[]{1,1,-2},grbVars);
grbModel.addConstr(expr2,GRB.GREATER_EQUAL,10,"expr2");
// 目标函数:x1+2*x2+3*x3
GRBLinExpr target = new GRBLinExpr();
target.addTerms(new double[]{1,2,3},grbVars);
grbModel.setObjective(target,GRB.MAXIMIZE);
// 开始求解
grbModel.optimize();
// 输出求解结果
System.out.println("最优解为:"+grbModel.get(GRB.DoubleAttr.ObjVal));
System.out.println("x1 = "+x1.get(GRB.DoubleAttr.X));
System.out.println("x2 = "+x2.get(GRB.DoubleAttr.X));
System.out.println("x3 = "+x3.get(GRB.DoubleAttr.X));
// 处理模型和环境
grbModel.dispose();
grbEnv.dispose();
}catch (Exception e){
e.printStackTrace();
}
}
}
求解结果
Set parameter Username
Academic license - for non-commercial use only - expires 2022-08-03
Gurobi Optimizer version 9.5.1 build v9.5.1rc2 (win64)
Thread count: 6 physical cores, 12 logical processors, using up to 12 threads
Optimize a model with 2 rows, 3 columns and 6 nonzeros
Model fingerprint: 0x5c13f6c7
Coefficient statistics:
Matrix range [1e+00, 2e+00]
Objective range [1e+00, 3e+00]
Bounds range [5e+00, 5e+01]
RHS range [1e+01, 1e+02]
Presolve removed 2 rows and 3 columns
Presolve time: 0.00s
Presolve: All rows and columns removed
Iteration Objective Primal Inf. Dual Inf. Time
0 1.1000000e+02 0.000000e+00 0.000000e+00 0s
Solved in 0 iterations and 0.00 seconds (0.00 work units)
Optimal objective 1.100000000e+02
最优解为:110.0
x1 = 50.0
x2 = 22.5
x3 = 5.0