【问题标题】:Dual variables Gurobi with C++使用 C++ 的双变量 Gurobi
【发布时间】: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


    【解决方案1】:

    对偶变量与线性约束相关,因此您应该使用GRBgetdblattrelement 来获取对偶值。索引可以从函数GRBgetconstrbyname 获得。例如

        int pIndex0 = 0, pIndex1 = 0, pIndex2 = 0;
        GRBgetconstrbyname(model, "c0", &pIndex0);
        GRBgetconstrbyname(model, "c1", &pIndex1);
        GRBgetconstrbyname(model, "c2", &pIndex2);
        double dual0=0, dual1=0, dual2=0;
        GRBgetdblattrelement(model, "Pi", pIndex0, &dual0);
        GRBgetdblattrelement(model, "Pi", pIndex1, &dual1);
        GRBgetdblattrelement(model, "Pi", pIndex2, &dual2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多