Hide navigation sidebar
Hide table of contents sidebar
Back to top
Toggle table of contents sidebar

# Qcp Examples

This section includes source code for all of the Gurobi qcp examples. The same source code can be found in the `examples` directory of the Gurobi distribution.

    /* Copyright 2025, Gurobi Optimization, LLC */

    /* This example formulates and solves the following simple QCP model:

         maximize    x
         subject to  x + y + z = 1
                     x^2 + y^2 <= z^2 (second-order cone)
                     x^2 <= yz        (rotated second-order cone)
                     x, y, z non-negative
    */

    #include <stdlib.h>
    #include <stdio.h>
    #include "gurobi_c.h"

    int
    main(int   argc,
         char *argv[])
    {
      GRBenv   *env   = NULL;
      GRBmodel *model = NULL;
      int       error = 0;
      double    sol[3];
      int       ind[3];
      double    val[3];
      double    obj[] = {1, 0, 0};
      int       qrow[3];
      int       qcol[3];
      double    qval[3];
      int       optimstatus;
      double    objval;

      /* Create environment */

      error = GRBloadenv(&env, "qcp.log");
      if (error) goto QUIT;

      /* Create an empty model */

      error = GRBnewmodel(env, &model, "qcp", 0, NULL, NULL, NULL, NULL, NULL);
      if (error) goto QUIT;

      /* Add variables */

      error = GRBaddvars(model, 3, 0, NULL, NULL, NULL, obj, NULL, NULL, NULL,
                         NULL);
      if (error) goto QUIT;

      /* Change sense to maximization */

      error = GRBsetintattr(model, GRB_INT_ATTR_MODELSENSE, GRB_MAXIMIZE);
      if (error) goto QUIT;

      /* Linear constraint: x + y + z = 1 */

      ind[0] = 0; ind[1] = 1; ind[2] = 2;
      val[0] = 1; val[1] = 1; val[2] = 1;

      error = GRBaddconstr(model, 3, ind, val, GRB_EQUAL, 1.0, "c0");
      if (error) goto QUIT;

      /* Cone: x^2 + y^2 <= z^2 */

      qrow[0] = 0; qcol[0] = 0; qval[0] = 1.0;
      qrow[1] = 1; qcol[1] = 1; qval[1] = 1.0;
      qrow[2] = 2; qcol[2] = 2; qval[2] = -1.0;

      error = GRBaddqconstr(model, 0, NULL, NULL, 3, qrow, qcol, qval,
                            GRB_LESS_EQUAL, 0.0, "qc0");
      if (error) goto QUIT;

      /* Rotated cone: x^2 <= yz */

      qrow[0] = 0; qcol[0] = 0; qval[0] = 1.0;
      qrow[1] = 1; qcol[1] = 2; qval[1] = -1.0;

      error = GRBaddqconstr(model, 0, NULL, NULL, 2, qrow, qcol, qval,
                            GRB_LESS_EQUAL, 0.0, "qc1");
      if (error) goto QUIT;

      /* Optimize model */

      error = GRBoptimize(model);
      if (error) goto QUIT;

      /* Write model to 'qcp.lp' */

      error = GRBwrite(model, "qcp.lp");
      if (error) goto QUIT;

      /* Capture solution information */

      error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
      if (error) goto QUIT;

      error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
      if (error) goto QUIT;

      error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, 3, sol);
      if (error) goto QUIT;

      printf("\nOptimization complete\n");
      if (optimstatus == GRB_OPTIMAL) {
        printf("Optimal objective: %.4e\n", objval);

        printf("  x=%.2f, y=%.2f, z=%.2f\n", sol[0], sol[1], sol[2]);
      } else if (optimstatus == GRB_INF_OR_UNBD) {
        printf("Model is infeasible or unbounded\n");
      } else {
        printf("Optimization was stopped early\n");
      }

    QUIT:

      /* Error reporting */

      if (error) {
        printf("ERROR: %s\n", GRBgeterrormsg(env));
        exit(1);
      }

      /* Free model */

      GRBfreemodel(model);

      /* Free environment */

      GRBfreeenv(env);

      return 0;
    }

    /* Copyright 2025, Gurobi Optimization, LLC */

    /* This example formulates and solves the following simple QCP model:

         maximize    x
         subject to  x + y + z = 1
                     x^2 + y^2 <= z^2 (second-order cone)
                     x^2 <= yz        (rotated second-order cone)
                     x, y, z non-negative
    */

    #include "gurobi_c++.h"
    using namespace std;

    int
    main(int   argc,
         char *argv[])
    {
      try {
        GRBEnv env = GRBEnv();

        GRBModel model = GRBModel(env);

        // Create variables

        GRBVar x = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "x");
        GRBVar y = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "y");
        GRBVar z = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "z");

        // Set objective

        GRBLinExpr obj = x;
        model.setObjective(obj, GRB_MAXIMIZE);

        // Add linear constraint: x + y + z = 1

        model.addConstr(x + y + z == 1, "c0");

        // Add second-order cone: x^2 + y^2 <= z^2

        model.addQConstr(x*x + y*y <= z*z, "qc0");

        // Add rotated cone: x^2 <= yz

        model.addQConstr(x*x <= y*z, "qc1");

        // Optimize model

        model.optimize();

        cout << x.get(GRB_StringAttr_VarName) << " "
             << x.get(GRB_DoubleAttr_X) << endl;
        cout << y.get(GRB_StringAttr_VarName) << " "
             << y.get(GRB_DoubleAttr_X) << endl;
        cout << z.get(GRB_StringAttr_VarName) << " "
             << z.get(GRB_DoubleAttr_X) << endl;

        cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl;

      } catch(GRBException e) {
        cout << "Error code = " << e.getErrorCode() << endl;
        cout << e.getMessage() << endl;
      } catch(...) {
        cout << "Exception during optimization" << endl;
      }

      return 0;
    }

    /* Copyright 2025, Gurobi Optimization, LLC */

    /* This example formulates and solves the following simple QCP model:

         maximize    x
         subject to  x + y + z = 1
                     x^2 + y^2 <= z^2 (second-order cone)
                     x^2 <= yz        (rotated second-order cone)
                     x, y, z non-negative
    */

    using System;
    using Gurobi;

    class qcp_cs
    {
      static void Main()
      {
        try {
          GRBEnv    env   = new GRBEnv("qcp.log");
          GRBModel  model = new GRBModel(env);

          // Create variables

          GRBVar x = model.AddVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "x");
          GRBVar y = model.AddVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "y");
          GRBVar z = model.AddVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "z");

          // Set objective

          GRBLinExpr obj = x;
          model.SetObjective(obj, GRB.MAXIMIZE);

          // Add linear constraint: x + y + z = 1

          model.AddConstr(x + y + z == 1.0, "c0");

          // Add second-order cone: x^2 + y^2 <= z^2

          model.AddQConstr(x*x + y*y <= z*z, "qc0");

          // Add rotated cone: x^2 <= yz

          model.AddQConstr(x*x <= y*z, "qc1");

          // Optimize model

          model.Optimize();

          Console.WriteLine(x.VarName + " " + x.X);
          Console.WriteLine(y.VarName + " " + y.X);
          Console.WriteLine(z.VarName + " " + z.X);

          Console.WriteLine("Obj: " + model.ObjVal + " " + obj.Value);

          // Dispose of model and env

          model.Dispose();
          env.Dispose();

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
      }
    }

    /* Copyright 2025, Gurobi Optimization, LLC */

    /* This example formulates and solves the following simple QCP model:

         maximize    x
         subject to  x + y + z = 1
                     x^2 + y^2 <= z^2 (second-order cone)
                     x^2 <= yz        (rotated second-order cone)
                     x, y, z non-negative
    */

    import com.gurobi.gurobi.*;

    public class Qcp {
      public static void main(String[] args) {
        try {
          GRBEnv    env   = new GRBEnv("qcp.log");
          GRBModel  model = new GRBModel(env);

          // Create variables

          GRBVar x = model.addVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "x");
          GRBVar y = model.addVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "y");
          GRBVar z = model.addVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "z");

          // Set objective

          GRBLinExpr obj = new GRBLinExpr();
          obj.addTerm(1.0, x);
          model.setObjective(obj, GRB.MAXIMIZE);

          // Add linear constraint: x + y + z = 1

          GRBLinExpr expr = new GRBLinExpr();
          expr.addTerm(1.0, x); expr.addTerm(1.0, y); expr.addTerm(1.0, z);
          model.addConstr(expr, GRB.EQUAL, 1.0, "c0");

          // Add second-order cone: x^2 + y^2 <= z^2

          GRBQuadExpr qexpr = new GRBQuadExpr();
          qexpr.addTerm(1.0, x, x);
          qexpr.addTerm(1.0, y, y);
          qexpr.addTerm(-1.0, z, z);
          model.addQConstr(qexpr, GRB.LESS_EQUAL, 0.0, "qc0");

          // Add rotated cone: x^2 <= yz

          qexpr = new GRBQuadExpr();
          qexpr.addTerm(1.0, x, x);
          qexpr.addTerm(-1.0, y, z);
          model.addQConstr(qexpr, GRB.LESS_EQUAL, 0.0, "qc1");

          // Optimize model

          model.optimize();

          System.out.println(x.get(GRB.StringAttr.VarName)
                             + " " +x.get(GRB.DoubleAttr.X));
          System.out.println(y.get(GRB.StringAttr.VarName)
                             + " " +y.get(GRB.DoubleAttr.X));
          System.out.println(z.get(GRB.StringAttr.VarName)
                             + " " +z.get(GRB.DoubleAttr.X));

          System.out.println("Obj: " + model.get(GRB.DoubleAttr.ObjVal) + " " +
                             obj.getValue());
          System.out.println();

          // Dispose of model and environment

          model.dispose();
          env.dispose();

        } catch (GRBException e) {
          System.out.println("Error code: " + e.getErrorCode() + ". " +
              e.getMessage());
        }
      }
    }

    function qcp()
    % Copyright 2025, Gurobi Optimization, LLC
    %
    % This example formulates and solves the following simple QCP model:
    %  maximize
    %      x
    %  subject to
    %      x + y + z = 1
    %      x^2 + y^2 <= z^2 (second-order cone)
    %      x^2 <= yz        (rotated second-order cone)
    %      x, y, z non-negative

    names = {'x', 'y', 'z'};
    model.varnames = names;

    % Set objective: x
    model.obj = [ 1 0 0 ];
    model.modelsense = 'max';

    % Add constraint: x + y + z = 1
    model.A   = sparse([1 1 1]);
    model.rhs = 1;
    model.sense = '=';

    % Add second-order cone: x^2 + y^2 <= z^2 using a sparse matrix
    model.quadcon(1).Qc = sparse([
        1 0  0;
        0 1  0;
        0 0 -1]);
    model.quadcon(1).q  = zeros(3,1);
    model.quadcon(1).rhs = 0.0;
    model.quadcon(1).name = 'std_cone';

    % Add rotated cone: x^2 <= yz using sparse triplet representation
    % Equivalent sparse matrix data:
    %model.quadcon(2).Qc = sparse([
    %    1 0  0;
    %    0 0 -1;
    %    0 0  0]);
    model.quadcon(2).Qrow = [1, 2]
    model.quadcon(2).Qcol = [1, 3]
    model.quadcon(2).Qval = [1, -1]
    % All-zero sparse 3-by-1 vector
    model.quadcon(2).q  = sparse(3,1);
    model.quadcon(2).rhs = 0.0;
    model.quadcon(2).name = 'rot_cone';

    gurobi_write(model, 'qcp.lp');

    result = gurobi(model);

    for j=1:3
        fprintf('%s %e\n', names{j}, result.x(j))
    end

    fprintf('Obj: %e\n', result.objval);
    end

    #!/usr/bin/env python3

    # Copyright 2025, Gurobi Optimization, LLC

    # This example formulates and solves the following simple QCP model:
    #  maximize    x
    #  subject to  x + y + z = 1
    #              x^2 + y^2 <= z^2 (second-order cone)
    #              x^2 <= yz        (rotated second-order cone)
    #              x, y, z non-negative

    import gurobipy as gp
    from gurobipy import GRB

    # Create a new model
    m = gp.Model("qcp")

    # Create variables
    x = m.addVar(name="x")
    y = m.addVar(name="y")
    z = m.addVar(name="z")

    # Set objective: x
    obj = 1.0 * x
    m.setObjective(obj, GRB.MAXIMIZE)

    # Add constraint: x + y + z = 1
    m.addConstr(x + y + z == 1, "c0")

    # Add second-order cone: x^2 + y^2 <= z^2
    m.addConstr(x**2 + y**2 <= z**2, "qc0")

    # Add rotated cone: x^2 <= yz
    m.addConstr(x**2 <= y * z, "qc1")

    m.optimize()

    for v in m.getVars():
        print(f"{v.VarName} {v.X:g}")

    print(f"Obj: {m.ObjVal:g}")

    # Copyright 2025, Gurobi Optimization, LLC
    #
    # This example formulates and solves the following simple QCP model:
    #  maximize
    #        x
    #  subject to
    #        x + y + z   =  1
    #        x^2 + y^2 <= z^2  (second-order cone)
    #        x^2 <= yz         (rotated second-order cone)
    #        x, y, z non-negative

    library(gurobi)
    library(Matrix)

    model <- list()

    model$A          <- matrix(c(1,1,1), nrow=1, byrow=T)
    model$modelsense <- 'max'
    model$obj        <- c(1,0,0)
    model$rhs        <- c(1)
    model$sense      <- c('=')

    # First quadratic constraint: x^2 + y^2 - z^2 <= 0
    qc1 <- list()
    qc1$Qc <- spMatrix(3, 3, c(1, 2, 3), c(1, 2, 3), c(1.0, 1.0, -1.0))
    qc1$rhs <- 0.0

    # Second quadratic constraint: x^2 - yz <= 0
    qc2 <- list()
    qc2$Qc <- spMatrix(3, 3, c(1, 2), c(1, 3), c(1.0, -1.0))
    qc2$rhs <- 0.0

    model$quadcon <- list(qc1, qc2)

    result <- gurobi(model)

    print(result$objval)
    print(result$x)

    # Clear space
    rm(model, result)

    ' Copyright 2025, Gurobi Optimization, LLC

    ' This example formulates and solves the following simple QCP model:
    '
    '     maximize    x
    '     subject to  x + y + z = 1
    '                 x^2 + y^2 <= z^2 (second-order cone)
    '                 x^2 <= yz        (rotated second-order cone)
    '                 x, y, z non-negative

    Imports Gurobi

    Class qcp_vb
        Shared Sub Main()
            Try
                Dim env As New GRBEnv("qcp.log")
                Dim model As New GRBModel(env)

                ' Create variables

                Dim x As GRBVar = model.AddVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "x")
                Dim y As GRBVar = model.AddVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "y")
                Dim z As GRBVar = model.AddVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "z")

                ' Set objective

                Dim obj As GRBLinExpr = x
                model.SetObjective(obj, GRB.MAXIMIZE)

                ' Add linear constraint: x + y + z = 1

                model.AddConstr(x + y + z = 1.0, "c0")

                ' Add second-order cone: x^2 + y^2 <= z^2

                model.AddQConstr(x * x + y * y <= z * z, "qc0")

                ' Add rotated cone: x^2 <= yz

                model.AddQConstr(x * x <= y * z, "qc1")

                ' Optimize model

                model.Optimize()

                Console.WriteLine(x.VarName & " " & x.X)
                Console.WriteLine(y.VarName & " " & y.X)
                Console.WriteLine(z.VarName & " " & z.X)

                Console.WriteLine("Obj: " & model.ObjVal & " " & obj.Value)

                ' Dispose of model and env

                model.Dispose()

                env.Dispose()
            Catch e As GRBException
                Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
            End Try
        End Sub
    End Class

Help and Feedback

Press `/` or click to search this documentation | Gurobi website | Gurobi community forum
Go to other Gurobi documentation | Gurobi download | Contact support