Basic linear equality constraint
AnsweredHello, I am pretty much beginner to optimization (I've studied it for like one year at my university and used matlab functions to do optimization) and I wanted something different/better so I've chosen Python-Gurobi.
My question is probably really stupid but I've spent whole day trying to solve following problem.
min x^2 + 2
y=-x+4
So basicly there are two feasible solution - intersections of parabola and line, and I want the point [1,3] to be found.
m = gp.Model()
x = m.addVar(name="x")
y = m.addVar(name="y")
m.setObjective(x*x + 2, GRB.MINIMIZE)
m.addConstr(y == x - 4)
m.optimize()
-
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 Daniel,
The model looks good. There is only one small detail missing. You are interested in the intersection of the parabola and a line but this relationship is missing, i.e., you are missing the equality \(x^2 +2 = -x + 4\). Please also note that there is a typo in your line constraint, as first you said you are interested in the line \(-x + 4\) but your code reads \(x -4\).
You could model your problem as
import gurobipy as gp
from gurobipy import *
m = gp.Model()
x = m.addVar(name="x")
y = m.addVar(name="y")
m.setObjective(y, GRB.MINIMIZE)
m.addConstr( x * x + 2 == - x + 4, "intersection equality")
m.addConstr( y == x * x + 2)
m.optimize()
# print values of the solution point
for v in m.getVars():
print('%s %g' % (v.varName, v.x))Note that the variable \(y\) is only there for convenience such that you don't have to compute it yourself, since it is determined by the value of \(x\). In other words, you could delete \(y\) from the problem by substituting it by \(x^2 +2\).
Since it seems like you may be working with more complex quadratic problems in the future, which may get non-convex quickly, don't forget to set the NonConvex parameter to 2.Best regards,
Jaromił0 -
Thank you very much for your answer, it is all clear now.
I will probably handle with piecewise-linear objective and linear constraints (I am dealing with Yasuda-Kasai financial planning model). But I wanted to try basic examples first.
Best regards,
Dan
0
Post is closed for comments.
Comments
3 comments