Adding constraints to the model

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

  // Add constraint: x + 2 y + 3 z <= 4
  GRBLinExpr expr;

  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");

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.

Search