OR-Tools中IntVar使用疑问:设置后未得整数值如何解决?
Ah, I get exactly what's going on here—you've hit a classic solver type mismatch! The problem isn't with how you're defining IntVar; it's with the solver you're using.
The Root Cause
GLOP_LINEAR_PROGRAMMING is Google OR-Tools' dedicated linear programming (LP) solver, which only handles continuous variables. Even if you declare a variable as IntVar, GLOP will ignore the integer constraint entirely and treat it like a regular continuous NumVar. That's why you're seeing non-integer values for those variables in your solution.
The Fix: Use a Mixed Integer Programming (MIP) Solver
To enforce integer constraints, you need to use a solver that supports mixed integer programming. OR-Tools comes with several great open-source options out of the box:
SCIP: A powerful, versatile MIP solver ideal for most use casesCBC: Another popular, reliable MIP solver
Example Code: Wrong vs. Right
Let's break down the difference with concrete code snippets.
Wrong (GLOP Solver, Ignores Integer Constraints)
from ortools.linear_solver import pywraplp # This solver doesn't handle integer variables at all! solver = pywraplp.Solver.CreateSolver('GLOP_LINEAR_PROGRAMMING') # Define variables x = solver.IntVar(0, 10, 'x') # GLOP will treat this as a continuous variable y = solver.NumVar(0.0, 10.0, 'y') # Add objective and constraints solver.Minimize(x + y) solver.Add(x + 2*y >= 5) # Solve and print results status = solver.Solve() if status == pywraplp.Solver.OPTIMAL: print(f'x (supposed to be integer): {x.solution_value()}') # Will output a non-integer print(f'y: {y.solution_value()}')
Right (MIP Solver, Enforces Integer Constraints)
from ortools.linear_solver import pywraplp # Use a MIP solver instead of GLOP solver = pywraplp.Solver.CreateSolver('SCIP') # Replace with 'CBC' if preferred # Same variable definitions as before x = solver.IntVar(0, 10, 'x') y = solver.NumVar(0.0, 10.0, 'y') # Same objective and constraints solver.Minimize(x + y) solver.Add(x + 2*y >= 5) # Solve and print results status = solver.Solve() if status == pywraplp.Solver.OPTIMAL: print(f'x (integer): {x.solution_value()}') # Now outputs an integer value! print(f'y: {y.solution_value()}')
Additional Tips
- Always verify a solver's capabilities before using it: LP solvers only handle continuous variables, while MIP solvers support mixes of integer and continuous variables.
- If you get a
FEASIBLEstatus instead ofOPTIMAL, the solver found a valid integer solution but not necessarily the best one. For small to medium problems,SCIPorCBCwill usually find the optimal solution quickly, but you can adjust solver parameters (like time limits) if needed for larger models.
内容的提问来源于stack exchange,提问作者Zain Khaishagi

