Preferred way to check if variable value is non zero
AnsweredUsing Python API, what is a preferred way to :
1. Check if variable value in a solution is non zero.
2. Get the list of non-zero variables.
For '1' I checked the examples and it does not seem to be consistent:
diet.py -> "buy[f].x > 0.0001"
facility.py -> "transport[w,p].x > 0"
mip2.py -> "v.x != 0"
-
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?. -
MIP solvers solve integer programs via a series of linear programming relaxations and in this process, small rounding errors are unavoidable in a world of floating-point arithmetic. For this reason, we usually recommend allowing for some tolerance when comparing the value of a variable with other numbers.
For a non-negative variable, it then suffices to check whether the value is greater than the tolerance, e.g. \(v.X > \epsilon\); if the variable can take both positive and negative values, you will have to check whether \(v.X > \epsilon\) or \(v.X < -\epsilon\).
A good value for the tolerance \(\epsilon\) could be something in the range of IntFeasTol (default 1e-5) or FeasibilityTol (default 1e-6) but may depend on your application or the variable type. (E.g. for the binary variables in sudoku.py, you can see that we use 0.5: solution[i,j,v] > 0.5.)
Note that some of the examples that are included with Gurobi are mostly meant to demonstrate how to use the API. In particular, mip2.py does not model any practical application and is a just very basic programming example for beginners. (And when you are just starting to work with Gurobi, it may be interesting to see these very small non-zero values so that you are aware of the issue...)
1 -
Thank you for your explanation. I would like to clarify one thing - let say that I am declaring variable as integer or binary, then what you are saying is that I cannot expect that its value in solution is integer or binary. Because from a user point of view, it is rather counter-intuitive. I would expect that a following comparison "var[i] == 1" yields true even though internally it might be represented as 1 - 1e-6 but should be considered as 1. Or as I understand that dealing with numerical issues might be non-trivial, at least provide some utility function that would have knowledge of all performed relaxations and be able to apply correct tolerance.
0 -
Yes, exactly, integer variables may take values within IntFeasTol of an integer number.
We do not round the resulting values (because this can create problems) but instead recommend that the users round the values themselves if they need truly integral values. You can find more information in this article.
0
Post is closed for comments.
Comments
4 comments