CPLEX OPL建模报错:Cannot use type dvar float+ for constraint如何解决?
Got it, let's break down why you're hitting this error and how to fix it quickly:
Why This Error Occurs
You declared travel_time_p as a decision variable (dvar float+), but you're trying to assign it a fixed, calculated value directly in a constraint. Decision variables are meant to be values the solver optimizes during runtime—you can't treat them like static parameters by setting them equal to distance_p[p1][p2]/velocity in a constraint. CPLEX throws this error because it can't reconcile a decision variable being used as a fixed value in a constraint definition.
The Most Common (and Simple) Fix
Since travel_time_p is just a derived value based on your known parameters (distance_p and velocity), it shouldn't be a decision variable at all. Instead, declare it as a regular parameter:
First, update the variable declaration:
float travel_time_p[plant][plant];
Then, initialize it before your constraints using an execute block in your model:
execute { for(var p1 in plant) { for(var p2 in plant) { if(p1 != p2) { travel_time_p[p1][p2] = distance_p[p1][p2]/velocity; } // Handle the case where p1 == p2 (typically set to 0, since travel time to the same plant is zero) else { travel_time_p[p1][p2] = 0; } } } }
Alternatively, if you know all distance_p values upfront, you can compute travel_time_p directly in your data file instead of using an execute block.
If You Must Keep It as a Decision Variable
In rare scenarios (e.g., if velocity is also a decision variable, or you need to account for uncertainty), you can rework the constraint to properly enforce the relationship instead of assigning a fixed value:
forall(p1 in plant, p2 in plant : p1 != p2) { travel_time_p[p1][p2] * velocity == distance_p[p1][p2]; }
This rearranges the equation to avoid division (which can cause numerical quirks) and sets up a valid equality constraint the solver can process, rather than trying to "hardcode" a value into a decision variable.
内容的提问来源于stack exchange,提问作者Natdanai I.

