Gurobi变量self.a与self.b返回0.0,如何获取其正确值?
Fixing Gurobi Variable Value Issue (Always 0.0)
The main problems with your code are that you're not creating a valid constraint involving your variables, and you haven't defined an objective function for Gurobi to optimize. Here's how to resolve this:
Breakdown of the Issues
- Invalid Constraint: In your
constraint1method, you're overwriting the variable references (lhs1andrhs1) with integers 2 and 3, which results in a trivial constraint (2 <= 3) that doesn't affect your variables at all. Your variables end up with no meaningful constraints beyond their lower bound of 0. - Missing Objective Function: Without an objective (something to maximize or minimize), Gurobi just returns any feasible solution. Since your variables only have a lower bound of 0, it defaults to that value.
Corrected Code
from gurobipy import GRB, Model class abc(object): def __init__(self): self.model = Model() def creatingvarriables(self): # Add variables (model.update() is not required here; addVar handles it automatically) self.a = self.model.addVar(lb=0, vtype=GRB.CONTINUOUS, name="y_") self.b = self.model.addVar(lb=0, vtype=GRB.CONTINUOUS, name="q_") # Define an objective function (example: maximize the sum of a and b) self.model.setObjective(self.a + self.b, GRB.MAXIMIZE) def constraint1(self): # Create a valid constraint using your variables (adjust this to match your actual needs) # Example: 2*a <= 3*b self.model.addConstr(2 * self.a, GRB.LESS_EQUAL, 3 * self.b, name="constraint1") def printvalues(self): # Run optimization self.model.optimize() # Check if optimization succeeded before accessing values if self.model.status == GRB.OPTIMAL: print(self.a.X) print(self.b.X) else: print("Optimization did not find an optimal solution.") if __name__ == "__main__": newobject = abc() newobject.creatingvarriables() newobject.constraint1() newobject.printvalues()
Key Fixes
- Valid Constraint: We now build a constraint using the actual variables instead of overwriting references. Adjust the constraint expression to match your specific problem requirements (e.g.,
self.a <= 2orself.b >= 3). - Objective Function: Added
setObjectiveto give Gurobi a clear goal (here, maximizing the sum ofaandb). Modify this to your desired objective (minimize, maximize, or a custom linear expression). - Status Check: Added a check for
GRB.OPTIMALto handle cases where optimization might fail (e.g., infeasible model).
Once these changes are applied, Gurobi will compute the optimal values for your variables based on your defined objective and constraints.
内容的提问来源于stack exchange,提问作者Danial Jalil
相关产品推荐
相关产品推荐

