簡體   English   中英

使用Java在Cplex中進行列明智的建模

[英]Column wise modeling in Cplex using Java

我想使用列明智的建模解決cplex中的一個簡單問題。 這是問題所在

maximize 2x + 3y
subject to   x<= 5
             y<=2
            x,y >=0

這是我必須編寫以解決它的代碼:

public static void Model_1() {
        try {
            //create new model
            IloCplex cplex = new IloCplex();
            //define variables
            IloNumVar x;
            IloNumVar y;
            IloObjective objective;
            objective = cplex.addMaximize();
            IloRange cons01;
            IloRange cons02;
            cons01 = cplex.addRange(0, 5, "c1");
            cons02 = cplex.addRange(0, 2, "c1");
            IloColumn new_col = cplex.column(objective, 2);
            IloColumn new_col2 = cplex.column(objective,3);
            new_col = new_col.and(cplex.column(cons01,1));
            new_col2 = new_col2.and(cplex.column(cons02,1));
            x = cplex.numVar(new_col, 0, Double.MAX_VALUE);
            y = cplex.numVar(new_col, 0, Double.MAX_VALUE);
//solve model
            if (cplex.solve()) {
                System.out.println("obj = "+cplex.getObjValue());
                System.out.println("x   = "+cplex.getValue(x));
                System.out.println("y   = "+cplex.getValue(y));
}
            else {
                System.out.println("Model not solved");
            }
            cplex.end();
        }
        catch (IloException exc) {
            exc.printStackTrace();
        }
    }

但是我沒有得到正確的解決方案。 我在編寫代碼時犯了任何錯誤?

嘗試調試此類問題時,將模型導出為LP格式以確保正確生成模型總是有用的。 為此,可以在調用cplex.solve之前添加以下代碼:

cplex.exportModel("model.lp");

如果這樣做,model.lp的內容如下所示:

Maximize
 obj: 2 x1 + 2 x2
Subject To
 c1: x1 + x2 - Rgc1  = 0
 c1: - Rgc1  = 0
Bounds
 0 <= Rgc1 <= 5
 0 <= Rgc1 <= 2
End

這可以說明您在程序中進行的兩次輸入錯誤。 即,您應該替換:

cons02 = cplex.addRange(0, 2, "c1");

cons02 = cplex.addRange(0, 2, "c2");

並且,您應該替換:

y = cplex.numVar(new_col, 0, Double.MAX_VALUE);

y = cplex.numVar(new_col2, 0, Double.MAX_VALUE);

進行這兩項更改后,model.lp如下所示:

Maximize
 obj: 2 x1 + 3 x2
Subject To
 c1: x1 - Rgc1  = 0
 c2: x2 - Rgc2  = 0
Bounds
 0 <= Rgc1 <= 5
 0 <= Rgc2 <= 2
End

並且,您從程序中獲得以下輸出:

obj = 16.0
x   = 5.0
y   = 2.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM