gpt4 book ai didi

java - 将约束添加到数组列表中的问题

转载 作者:行者123 更新时间:2023-12-02 10:57:18 26 4
gpt4 key购买 nike

我正在学习使用 Java API 编写优化问题代码,并且在将以下简单 LP 的最后约束保存到名为 Constraints 的数组列表中时遇到问题。如果没有这个,代码就会运行,但是,当我激活这行代码时,会弹出错误:Constraints.add(model.addEq(proportionalWeight[j], y));
而不是以下行:
model.addEq(proportionalWeight[j], y);

MWE:

import ilog.concert.*;
import ilog.cplex.*;
import java.util.*;

public class SimpleLP {

public static void main(String[] args) {
Solve();
}
public static void Solve() {
int n = 4;
int m = 3;

double[] p = { 310.0, 380.0, 350.0, 285.0 };
double[] v = { 480.0, 650.0, 580.0, 390.0 };
double[] a = { 18.0, 15.0, 23.0, 12.0 };
double[] c = { 10.0, 16.0, 8.0 };
double[] V = { 6800.0, 8700.0, 5300.0 };

try {

IloCplex model = new IloCplex();

IloNumVar[][] x = new IloNumVar[n][];
for (int i = 0; i < n; i++) {
x[i] = model.numVarArray(m, 0, Double.MAX_VALUE);
}

IloNumVar y = model.numVar(0, Double.MAX_VALUE);

IloLinearNumExpr obj = model.linearNumExpr();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
obj.addTerm(p[i], x[i][j]);
}
}

model.addMaximize(obj);

for (int i = 0; i < n; i++) {
model.addLe(model.sum(x[i]), a[i]);
}


List<IloRange> Constraints = new ArrayList<IloRange>();

IloLinearNumExpr [] usedWeightCap = new IloLinearNumExpr[m];
IloLinearNumExpr [] usedVolumeCap = new IloLinearNumExpr[m];
IloLinearNumExpr [] proportionalWeight = new IloLinearNumExpr[m];

for (int j = 0; j < m; j++) {
usedWeightCap[j] = model.linearNumExpr();
usedVolumeCap[j] = model.linearNumExpr();
proportionalWeight[j] = model.linearNumExpr();

for (int i = 0; i < n; i++) {
usedWeightCap[j].addTerm(1.0, x[i][j]);
usedVolumeCap[j].addTerm(v[i], x[i][j]);
proportionalWeight[j].addTerm(1/c[j], x[i][j]);
}
}
for (int j = 0; j < m; j++) {

Constraints.add(model.addLe(usedWeightCap[j], c[j]));

Constraints.add(model.addLe(usedVolumeCap[j], V[j]));

//model.addEq(model.prod(1/c[j], usedWeightCap[j]), y);
//Constraints.add(model.addEq(proportionalWeight[j], y)); /*This is my problem that I cannot add this constraint into the list*/
model.addEq(proportionalWeight[j], y);
}
if (model.solve()) {
System.out.println("Objective Value: "+ model.getObjValue());
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.println("x*["+(i+1)+"]"+"["+(j+1)+"] : "+model.getValue(x[i][j]));
}
}
System.out.println("y* : "+ model.getValue(y));
} else {
System.out.println("Problem not solved :(");
}

model.end();

} catch (IloException ex) {
ex.printStackTrace();
}
}
}
<小时/>

如果有人能帮助我解决这个问题,我将不胜感激。
问候,
巴曼

最佳答案

我应该使用 model.diff(proportionalWeight[j], y), 0.0); 而不是 .addEq();

关于java - 将约束添加到数组列表中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51627077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com