Different ways of defining quadratic expressions
AnsweredMy question is very simple perhaps, but I'm new to Gurobi and I would like to be very sure about the answer.
So, assume we have a one-dimensional MVar in our model:
from gurobipy import *
model = Model()
x = model.addMVar(1000, vtype=GRB.INTEGER)
Do I figure it right that the quadratic expression
expr = x@x
is mathematically equivalent to
expr = quicksum(var*var for var in x.tolist())
?
There are certainly under-the-hood differences in the implementation since print(expr) results in completely different output for these two cases, but I presume the mathematical sense is the same.
Thanks.
-
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?. -
Yes, those two expressions are mathematically equivalent. You can test this by adding both expressions to the model in separate constraints, writing out an LP file with Model.write(), then visually inspecting the LP file to compare the two constraints. For example, the following code
import gurobipy as gp
m = gp.Model()
x = m.addMVar(5, name='x')
# Add constraint in two different ways
m.addConstr(x @ x == 1, name='approach1')
m.addConstr(gp.quicksum(var*var for var in x.tolist()) == 1, name='approach2')
# Write results to LP file
m.write('foo.lp')creates a \( \texttt{foo.lp} \) model file with the exact same constraint repeated twice:
Minimize
Subject To
approach1: [ x[0] ^2 + x[1] ^2 + x[2] ^2 + x[3] ^2 + x[4] ^2 ] = 1
approach2: [ x[0] ^2 + x[1] ^2 + x[2] ^2 + x[3] ^2 + x[4] ^2 ] = 1
Bounds
End1 -
Thanks. I have been looking for a way to transform these expressions to some "canonical form" to compare them but I haven't come up with the idea of exporting the model to file.
0
Post is closed for comments.
Comments
3 comments