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

# Qp Examples

This section includes source code for all of the Gurobi qp 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 QP model:

         minimize    x^2 + x*y + y^2 + y*z + z^2 + 2 x
         subject to  x + 2 y + 3 z >= 4
                     x +   y       >= 1
                     x, y, z non-negative

       It solves it once as a continuous model, and once as an integer model.
    */

    #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];
      int       qrow[5];
      int       qcol[5];
      double    qval[5];
      char      vtype[3];
      int       optimstatus;
      double    objval;

      /* Create environment */

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

      /* Create an empty model */

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

      /* Add variables */

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

      /* Quadratic objective terms */

      qrow[0] = 0; qrow[1] = 0; qrow[2] = 1; qrow[3] = 1; qrow[4] = 2;
      qcol[0] = 0; qcol[1] = 1; qcol[2] = 1; qcol[3] = 2; qcol[4] = 2;
      qval[0] = 1; qval[1] = 1; qval[2] = 1; qval[3] = 1; qval[4] = 1;

      error = GRBaddqpterms(model, 5, qrow, qcol, qval);
      if (error) goto QUIT;

      /* Linear objective term */

      error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, 0, 2.0);
      if (error) goto QUIT;

      /* First constraint: x + 2 y + 3 z <= 4 */

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

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

      /* Second constraint: x + y >= 1 */

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

      error = GRBaddconstr(model, 2, ind, val, GRB_GREATER_EQUAL, 1.0, "c1");
      if (error) goto QUIT;

      /* Optimize model */

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

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

      error = GRBwrite(model, "qp.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=%.4f, y=%.4f, z=%.4f\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");
      }

      /* Modify variable types */

      vtype[0] = GRB_INTEGER; vtype[1] = GRB_INTEGER; vtype[2] = GRB_INTEGER;

      error = GRBsetcharattrarray(model, GRB_CHAR_ATTR_VTYPE, 0, 3, vtype);
      if (error) goto QUIT;

      /* Optimize model */

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

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

      error = GRBwrite(model, "qp2.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=%.4f, y=%.4f, z=%.4f\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 QP model:

         minimize    x^2 + x*y + y^2 + y*z + z^2 + 2 x
         subject to  x + 2 y + 3 z >= 4
                     x +   y       >= 1
                     x, y, z non-negative

       It solves it once as a continuous model, and once as an integer model.
    */

    #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, 1.0, 0.0, GRB_CONTINUOUS, "x");
        GRBVar y = model.addVar(0.0, 1.0, 0.0, GRB_CONTINUOUS, "y");
        GRBVar z = model.addVar(0.0, 1.0, 0.0, GRB_CONTINUOUS, "z");

        // Set objective

        GRBQuadExpr obj = x*x + x*y + y*y + y*z + z*z + 2*x;
        model.setObjective(obj);

        // Add constraint: x + 2 y + 3 z >= 4

        model.addConstr(x + 2 * y + 3 * z >= 4, "c0");

        // Add constraint: x + y >= 1

        model.addConstr(x + y >= 1, "c1");

        // 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;

        // Change variable types to integer

        x.set(GRB_CharAttr_VType, GRB_INTEGER);
        y.set(GRB_CharAttr_VType, GRB_INTEGER);
        z.set(GRB_CharAttr_VType, GRB_INTEGER);

        // 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 QP model:

         minimize    x^2 + x*y + y^2 + y*z + z^2 + 2 x
         subject to  x + 2 y + 3 z >= 4
                     x +   y       >= 1
                     x, y, z non-negative

       It solves it once as a continuous model, and once as an integer model.
    */

    using System;
    using Gurobi;

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

          // Create variables

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

          // Set objective

          GRBQuadExpr obj = x*x + x*y + y*y + y*z + z*z + 2*x;
          model.SetObjective(obj);

          // Add constraint: x + 2 y + 3 z >= 4

          model.AddConstr(x + 2 * y + 3 * z >= 4.0, "c0");

          // Add constraint: x + y >= 1

          model.AddConstr(x + y >= 1.0, "c1");

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

          // Change variable types to integer

          x.VType = GRB.INTEGER;
          y.VType = GRB.INTEGER;
          z.VType = GRB.INTEGER;

          // 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 QP model:

         minimize    x^2 + x*y + y^2 + y*z + z^2 + 2 x
         subject to  x + 2 y + 3 z >= 4
                     x +   y       >= 1
                     x, y, z non-negative

       It solves it once as a continuous model, and once as an integer model.
    */

    import com.gurobi.gurobi.*;

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

          // Create variables

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

          // Set objective

          GRBQuadExpr obj = new GRBQuadExpr();
          obj.addTerm(1.0, x, x);
          obj.addTerm(1.0, x, y);
          obj.addTerm(1.0, y, y);
          obj.addTerm(1.0, y, z);
          obj.addTerm(1.0, z, z);
          obj.addTerm(2.0, x);
          model.setObjective(obj);

          // Add constraint: x + 2 y + 3 z >= 4

          GRBLinExpr expr = new GRBLinExpr();
          expr.addTerm(1.0, x); expr.addTerm(2.0, y); expr.addTerm(3.0, z);
          model.addConstr(expr, GRB.GREATER_EQUAL, 4.0, "c0");

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

          // 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();

          // Change variable types to integer

          x.set(GRB.CharAttr.VType, GRB.INTEGER);
          y.set(GRB.CharAttr.VType, GRB.INTEGER);
          z.set(GRB.CharAttr.VType, GRB.INTEGER);

          // Optimize again

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

          // Dispose of model and environment

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

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

    function qp()
    % Copyright 2025, Gurobi Optimization, LLC
    %
    % This example formulates and solves the following simple QP model:
    %  minimize
    %      x^2 + x*y + y^2 + y*z + z^2 + 2 x
    %  subject to
    %      x + 2 y + 3 z >= 4
    %      x +   y       >= 1
    %      x, y, z non-negative
    %
    % It solves it once as a continuous model, and once as an integer
    % model.

    names = {'x', 'y', 'z'};
    model.varnames = names;
    model.Q = sparse([1 0.5 0; 0.5 1 0.5; 0 0.5 1]);
    model.A = sparse([1 2 3; 1 1 0]);
    model.obj = [2 0 0];
    model.rhs = [4 1];
    model.sense = '>';

    gurobi_write(model, 'qp.lp');

    results = gurobi(model);

    for v=1:length(names)
        fprintf('%s %e\n', names{v}, results.x(v));
    end

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

    model.vtype = 'B';

    results  = gurobi(model);

    for v=1:length(names)
        fprintf('%s %e\n', names{v}, results.x(v));
    end

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

    end

    #!/usr/bin/env python3

    # Copyright 2025, Gurobi Optimization, LLC

    # This example formulates and solves the following simple QP model:
    #  minimize
    #      x^2 + x*y + y^2 + y*z + z^2 + 2 x
    #  subject to
    #      x + 2 y + 3 z >= 4
    #      x +   y       >= 1
    #      x, y, z non-negative
    #
    # It solves it once as a continuous model, and once as an integer model.

    import gurobipy as gp
    from gurobipy import GRB

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

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

    # Set objective: x^2 + x*y + y^2 + y*z + z^2 + 2 x
    obj = x**2 + x * y + y**2 + y * z + z**2 + 2 * x
    m.setObjective(obj)

    # Add constraint: x + 2 y + 3 z >= 4
    m.addConstr(x + 2 * y + 3 * z >= 4, "c0")

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

    m.optimize()

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

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

    x.VType = GRB.INTEGER
    y.VType = GRB.INTEGER
    z.VType = GRB.INTEGER

    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 QP model:
    #  minimize
    #        x^2 + x*y + y^2 + y*z + z^2 + 2 x
    #  subject to
    #        x + 2 y + 3z >= 4
    #        x +   y      >= 1
    #        x, y, z non-negative

    library(gurobi)

    model <- list()

    model$A     <- matrix(c(1,2,3,1,1,0), nrow=2, byrow=T)
    model$Q     <- matrix(c(1,0.5,0,0.5,1,0.5,0,0.5,1), nrow=3, byrow=T)
    model$obj   <- c(2,0,0)
    model$rhs   <- c(4,1)
    model$sense <- c('>', '>')

    result <- gurobi(model)

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

    model$vtype <- c('I', 'I', 'I')

    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 QP model:
    '
    '     minimize    x^2 + x*y + y^2 + y*z + z^2 + 2 x
    '     subject to  x + 2 y + 3 z >= 4
    '                 x +   y       >= 1
    '                 x, y, z non-negative
    '
    '   It solves it once as a continuous model, and once as an integer model.
    '

    Imports Gurobi

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

                ' Create variables

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

                ' Set objective

                Dim obj As New GRBQuadExpr()
                obj = x*x + x*y + y*y + y*z + z*z + 2*x
                model.SetObjective(obj)

                ' Add constraint: x + 2 y + 3 z >= 4

                model.AddConstr(x + 2 * y + 3 * z >= 4.0, "c0")

                ' Add constraint: x + y >= 1

                model.AddConstr(x + y >= 1.0, "c1")

                ' 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)

                ' Change variable types to integer

                x.VType = GRB.INTEGER
                y.VType = GRB.INTEGER
                z.VType = GRB.INTEGER

                ' 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