Skip to main content

Preferred way to check if variable value is non zero




  • Silke Horn
    Gurobi Staff Gurobi Staff

    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, 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, 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...)



  • Grzegorz Siekaniec
    First Comment

    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.

  • Silke Horn
    Gurobi Staff Gurobi Staff

    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.


Please sign in to leave a comment.