【发布时间】:2020-06-28 19:00:52
【问题描述】:
我正在使用带有 C++ 接口的 Gurobi811 求解线性程序,我想恢复对偶变量。文档中写到对应的属性是Pi,但是语法不明确。这是一个有两个变量和三个约束的简单线性规划的例子,问题是得到c0、c1和C2对应的对偶变量。请有任何建议。
#include "gurobi_c++.h"
#include <stdlib.h>
using namespace std;
int
main(int argc,
char *argv[])
{
GRBenv *env = NULL;
GRBmodel *model = NULL;
int error = 0;
double sol[2];
int ind[2];
double val[2];
double obj[2];
char vtype[2];
int optimstatus;
double objval;
error = GRBloadenv(&env, "LP.log");
if (error) throw;
error = GRBnewmodel(env, &model, "LP", 0, NULL, NULL, NULL, NULL, NULL);
if (error) throw;
obj[0] = -2; obj[1] = +5;
vtype[0] = GRB_CONTINUOUS; vtype[1] = GRB_CONTINUOUS;
error = GRBaddvars(model, 2, 0, NULL, NULL, NULL, obj, 0, NULL, vtype,
NULL);
if (error) throw;
ind[0] = 0; ind[1] = 1;
val[0] = 2; val[1] = 3;
error = GRBaddconstr(model, 2, ind, val, GRB_LESS_EQUAL, 30.0, "c0");
if (error) throw;
ind[0] = 0; ind[1] = 1;
val[0] = 4; val[1] = -9;
error = GRBaddconstr(model, 2, ind, val, GRB_LESS_EQUAL, 0.0, "c1");
if (error) throw;
ind[0] = 0; ind[1] = 1;
val[0] = 1; val[1] = 1;
error = GRBaddconstr(model, 2, ind, val, GRB_GREATER_EQUAL, 5.0, "c2");
if (error) throw;
error = GRBoptimize(model);
if (error) throw;
/* Capture solution information */
error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
if (error) throw;
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (error) throw;
error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, 2, sol);
if (error) throw;
printf("\nOptimization complete\n");
if (optimstatus == GRB_OPTIMAL) {
printf("Optimal objective: %.4e\n", objval);
printf(" x1=%.4e, x2=%.4e\n", sol[0], sol[1]);
} else if (optimstatus == GRB_INF_OR_UNBD) {
printf("Model is infeasible or unbounded\n");
} else {
printf("Optimization was stopped early\n");
}
if (error) {
printf("ERROR: %s\n", GRBgeterrormsg(env));
//exit(1);
}
GRBfreemodel(model); GRBfreeenv(env);
return 0;
}
【问题讨论】:
标签: c++ linear-programming gurobi