• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

线性最优解java实现+Cplex java调用

互联网 diligentman 4天前 5次浏览

一:cplex的使用:
1.1 导入cplex.jar,包的地址:https://pan.baidu.com/s/1Q0Bv24EQdelV2rY-IrLoZQ 提取码:xn14
1.2 将cplex1290.dll (地址:https://pan.baidu.com/s/1sQXqYTSJWywwaZt5AHVkZQ 提取码:nm0l)添加到VM option中,这里以IDEA为例,
线性最优解java实现+Cplex java调用
线性最优解java实现+Cplex java调用
同样eclipse
线性最优解java实现+Cplex java调用
**二、求解问题。

  1. 一个简单的线性规划问题:**
    maxs.t.x1+2×2+3×3
    −x1+x2+x3≤20
    x1−3×2+x3≤30
    0≤x1≤40

java 中的 cplex 代码如下:

import ilog.concert.IloException;
import ilog.concert.IloNumVar;
import ilog.cplex.IloCplex;
 
public class LP1 {
 
 public static void main(String[] args) {
  try {
   IloCplex cplex = new IloCplex(); // creat a model
   
   double[] lb = {0.0, 0.0, 0.0};
   double[] ub = {40.0, Double.MAX_VALUE, Double.MAX_VALUE};
   IloNumVar[] x = cplex.numVarArray(3, lb, ub);
   
   double[] objvals = {1.0, 2.0, 3.0};
   cplex.addMaximize(cplex.scalProd(x, objvals));
   
   double[] coeff1 = {-1.0, 1.0, 1.0};
   double[] coeff2 = {1.0, -3.0, 1.0};
   
   cplex.addLe(cplex.scalProd(x, coeff1), 20.0);
   cplex.addLe(cplex.scalProd(x, coeff2), 30.0);
   
   if (cplex.solve()) {
    cplex.output().println("Solution status = " + cplex.getStatus());
    cplex.output().println("Solution value = " + cplex.getObjValue());
    double[] val = cplex.getValues(x);
    for (int j = 0; j < val.length; j++)
     cplex.output().println("x" + (j+1) + "  = " + val[j]);
   }
   cplex.end();
   
  } catch (IloException e) {
   System.err.println("Concert exception caught: " + e);
  }
 }
}

输出结果:

Tried aggregator 1 time.

N

o LP presolve or aggregator reductions.

Presolve time = 0.00 sec. (0.00 ticks)

Iteration log . . .

Iteration: 1 Dual infeasibility = 0.000000

Iteration: 2 Dual objective = 202.500000

Solution status = Optimal

Solution value = 202.5

x1 = 40.0
x2 = 17.5
x3 = 42.5

这里注意一下,求的是线性公式的最大值,而在MATLAB中利用x=linprog(f,[],[],Aeq,beq,lb);求解的是最小值(我怎么调试都不一致的原因),这里的参数就不在赘述了。
还有就是设置cplex API在https://wenku.baidu.com/view/7095dd76777f5acfa1c7aa00b52acfc789eb9fed.html有介绍(虽然是c#的,但是java可以借鉴。

三 线性最优解的java实现
代码地址:https://pan.baidu.com/s/1UeyQdPLMideXKqUaDBFYZQ 提取码:rte1
里面有详细注解,这里就不再解释,希望对大家有帮助!

借鉴:https://blog.csdn.net/robert_chen1988/article/details/78678289 ,感谢这位博主的文章。


喜欢 (0)