Quadratic Programming (QP)with gurobipy,why the answer is wrong?
Answeredimport gurobipy as gp
from gurobipy import *
import numpy as np
a = np.array([-1,-1,-1,-1])
b = np.array([1, 1, 1, 1])
c = np.array([1, 1, 1, 1])
model = gp.Model()
x = model.addMVar(4, vtype=GRB.CONTINUOUS)
model.addConstr(x >= a)
model.addConstr(x <= b)
model.setObjective(x@x+x@c, GRB.MINIMIZE)
model.write('model_4.mps')
model.optimize()
# Output
print('obj=', model.objVal)
for v in model.getVars():
print(v.varName, ':', v.x)
My code is above, I want to solve a simple QP here, I think the optimal solution should be x =-1/2c=[-0.5,-0.5,-0.5,-0.5], but the solver returns the following result to me, I just want to know where is the wrong? Can any one help me? Thanks sooooo much!
Academic license - for non-commercial use only - expires 2023-02-19
Gurobi Optimizer version 9.5.1 build v9.5.1rc2 (win64)
Thread count: 6 physical cores, 12 logical processors, using up to 12 threads
Optimize a model with 8 rows, 4 columns and 8 nonzeros
Model fingerprint: 0x8fab40bf
Model has 4 quadratic objective terms
Coefficient statistics:
Matrix range [1e+00, 1e+00]
Objective range [1e+00, 1e+00]
QObjective range [2e+00, 2e+00]
Bounds range [0e+00, 0e+00]
RHS range [1e+00, 1e+00]
Presolve removed 8 rows and 4 columns
Presolve time: 0.00s
Presolve: All rows and columns removed
Barrier solved model in 0 iterations and 0.00 seconds (0.00 work units)
Optimal objective 0.00000000e+00
obj= 0.0
C0 : 0.0
C1 : 0.0
C2 : 0.0
C3 : 0.0
Process finished with exit code 0
-
So it is because I forget to add the LB and UB in the definition of the decision variable x?
0 -
By default, variables added to the model with Model.addMVar(), Model.addVar(), and Model.addVars() have a lower bound of \( 0 \) and no upper bound.
If you specify your lower and upper bounds on \( x \) by adding \( \texttt{lb=a} \) and \( \texttt{ub=b} \) to your call to Model.addMVar(), you obtain the expected optimal solution:
obj= -1.0
C0 : -0.5
C1 : -0.5
C2 : -0.5
C3 : -0.50
Please sign in to leave a comment.
Comments
2 comments