0%

JOptimizer解决LP问题

JOptimizer解决LP问题

可以使用JOptimizer来解决LP问题

1
2
3
4
5
<dependency>
<groupId>com.joptimizer</groupId>
<artifactId>joptimizer</artifactId>
<version>5.0.0</version>
</dependency>

解决问题

1
2
3
4
5
6
/** minimize 4x+3Y 
* Subject to
* 8x+6y <= 25
* 3x+4y >= 15
* x,y >= 0
*/

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(new double[]{4.0, 3.0}, 0); //minimize 4x+3y

ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[4];

// 不等式中都以G.x < h的形式出现
// x >= 0
inequalities[0] = new LinearMultivariateRealFunction(new double[]{-1.0, 0.00}, 0.0);
// y >= 0
inequalities[1] = new LinearMultivariateRealFunction(new double[]{0.0, -1.00}, 0.0);
// 8x+6y <= 25
inequalities[2] = new LinearMultivariateRealFunction(new double[]{8, 6}, -25);
// 3x+4y >= 15
inequalities[3] = new LinearMultivariateRealFunction(new double[]{-3, -4}, 15);

OptimizationRequest or = new OptimizationRequest();
or.setF0(objectiveFunction);
or.setFi(inequalities);
// or.setToleranceFeas(JOptimizer.DEFAULT_FEASIBILITY_TOLERANCE/10);
// or.setTolerance(JOptimizer.DEFAULT_TOLERANCE/10);
// or.setMaxIteration(2000);

//optimization
JOptimizer opt = new JOptimizer();
opt.setOptimizationRequest(or);

try {
opt.optimize();
} catch (Exception e) {
e.printStackTrace();
}

if (opt.getOptimizationResponse() != null) {
double[] sol = opt.getOptimizationResponse().getSolution();

for (int i = 0; i < sol.length / 2; i++) {
System.out.println("x" + (i + 1) + ": " + Math.round(sol[i]) + "\ty" + (i + 1) + ": " + Math.round(sol[i + 1]));
}
}

结果为

1
x1: 0    y1: 4

欢迎关注我的其它发布渠道