How to add a constraint to express the objective function as an even number?
AnsweredDear staff:
I now want to add a constraint, which means that the value of the objective function is even. The objective function is the sum of multiple items, and quicksum() is used. Is it impossible to use %?
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hi,
Using the % operation is not possible in Gurobi.
One way of modeling an even objective is to introduce an additional integer variable \(\texttt{objvar}\) which represents your objective and add an equality constraint
objvar = 2 * dummyvar
where \(\texttt{dummyvar}\) is an integer variable as well.
Best regards,
Jaromił0 -
Thank you so much for the response, Sir.
I added an integer variable u and a constraint objvar=2*u . An error like " Quadratic equality constraints are non-convex. Set NonConvex parameter to 2 to solve model." appeared. Then I added Model.params.NonConvex = 2, and the program can run normally. May I know the reason?
Looking forward for your reply.
0 -
Hi,
Could you share the code snippet of you added the variables and the equality constraint?
Best regards,
Jaromił0 -
Thank you, Sir.
Here is the added code.
u=Model.addVar(vtype=GRB.INTEGER)
Model.addConstr(quicksum((ctt[i,j])**2 for i in range(1,n+1) for j in range(1,n+1))==2*u)0 -
Hi,
The left hand side of the constraint is \(\sum x_i^2\) which is quadratic. The resulting equality constraint then reads
\[ \sum x_i^2 - 2\cdot u = 0\]Non-linear equality constraints are non-convex. Thus, by adding this equality constraint, your problem becomes non-convex. In order to solve non-convex problems with Gurobi, you have to set the parameter NonConvex to 2.
Best regards,
Jaromił0 -
Dear Sir,
That's it! I understand. Thank you very much for your answer!
0
Post is closed for comments.
Comments
7 comments