Documentation

Adding constraints to the model

The next step in the example is to add the linear constraints. The first constraint is added here:


      // Add constraint: x + 2 y + 3 z <= 4
      expr = new GRBLinExpr();
      expr.addTerm(1.0, x); expr.addTerm(2.0, y); expr.addTerm(3.0, z);
      model.addConstr(expr, GRB.LESS_EQUAL, 4.0, "c0");

As with variables, constraints are always associated with a specific model. They are created using the addConstr() or addConstrs() methods on the model object.

The first argument to addConstr() is the left-hand side of the constraint. We built the left-hand side by first creating an empty linear expression object, and then adding three terms to it. The second argument is the constraint sense (GRB_LESS_EQUAL, GRB_GREATER_EQUAL, or GRB_EQUAL). The third argument is the right-hand side (a constant in our example). The final argument is the constraint name. Several signatures are available for addConstr(). Please consult the Gurobi Reference Manual for details.

The second constraint is created in a similar manner:


      // Add constraint: x + y >= 1
      expr = new GRBLinExpr();
      expr.addTerm(1.0, x); expr.addTerm(1.0, y);
      model.addConstr(expr, GRB.GREATER_EQUAL, 1.0, "c1");