Is it okay to input the coefficient of Gurobi linexpr as str type?
AnsweredDear Gurobi support team,
I am posting this to ask about data types related to Gurobi linexpr.
I'm currently experimenting with a fairly large MIP model in a Python 3.8 environment. So when creating the model, some coefficients are read from an external file. During this process, a bit silly, I coded some coefficients to be read as strings rather than numbers.
(These coefficients are all 0 or 1.)
For example, the written code was in fact something like this:
model.addConstr('1'*x[0]+ '1.5'*x[1] <= 1.0)
In fact, I intended this:
model.addConstr(1.0*x[0]+ 1.5*x[1] <= 1.0)
My experiments have been going on for quite some time already. The reason I only found out about this now is because no errors occurred.
I ran some code related to linexpr in the Python console, and the following result came out.
> x[1] = '1.032'*x[2]+ 2*x[3]
> print(x[1].getCoeff(0))
1.032
> print(x[1].getCoeff(1))
2.0
> print(type(x[1].getCoeff(0)))
<class 'float'>
> x[1] = '1.032'*x[2]+ 2*x[3] + '3'
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "src/gurobipy/linexpr.pxi", line 450, in gurobipy.LinExpr.__add__
File "src/gurobipy/linexpr.pxi", line 181, in gurobipy.LinExpr.add
TypeError: can't multiply sequence by non-int of type 'float'
So, in Gurobi linexpr:
- the coefficient of each variable is automatically converted to float even when entered as str.
- the constant(RHS) must be entered only as a number.
Is this right?
I'm worried about whether the models for my experiment had been generated as I intended.
I also checked the MPS files saved for the experiment, and it doesn't seem to be problematic... But I'd like to get a confirmation from Gurobi team.
This may seem like a silly question, but I'd appreciate an answer.
Thank you in advance.
Best regards,
Cathy
-
Hi Cathy,
This is an effect of Python's duck typing. The string holding a floating point number will be casted into a floating point number. Please note that even though this works as expected, it is not recommended to use string floats when working with Gurobi objects. The string formating may depend on the machine's locale settings, i.e., on some system the decimal '.' will be a ',' which completely messes up your script. Thus, it is best to turn any string values into floating point numbers before working with them.
Best regards,
Jaromił0 -
Dear Jaromił,
thank you very much for the helpful answer. I've modified the relevant lines in the script as you recommended. Thanks!
Regards,
Cathy0
Please sign in to leave a comment.
Comments
2 comments