使用JuMP与Julia求解优化问题时遭遇类型错误求助
Hey there! Let's break down this error you're hitting with your JuMP optimization problem. The core issue here is super clear from the error message: when you tried to add constraint 2, you passed an integer value (Int64) where JuMP expects a JuMP Model object.
What's causing this?
Chances are one of two things happened:
- You either never properly created a JuMP Model instance assigned to
m, or - You accidentally overwrote the
mvariable later in your code with an integer (like usingmas a loop counter, index, or assigning it a numeric value likem = 3).
JuMP's macros like @constraint rely on the first argument being the model you built (the container for all your variables and constraints), so if m is an integer instead, it throws that error.
How to fix it
Double-check your model initialization
Make sure you start by creating a valid JuMP Model before defining variables/constraints. For example:# Create a basic JuMP model (use a solver-specific one if needed, e.g., Model(Gurobi.Optimizer())) m = Model()This assigns a proper
Modeltype tom, not an integer.Avoid variable name conflicts
Scan your code to see if you reusedmfor something else before constraint 2. For example, if you have a line likem = 5orfor m in 1:10somewhere above, that's overwriting your model variable with an integer. Rename that integer variable to something else (likeidxorcounter) to keepmreserved for your JuMP model.Verify constraint 2's syntax
Ensure constraint 2 starts with the model object. A correct constraint looks like this:# Example constraint using the model m @constraint(m, your_constraint_expression_here)Replace
your_constraint_expression_herewith your actual constraint logic, but make sure the first argument is definitely your JuMP model, not an integer.
Quick working example
Here's a tiny snippet to show the correct flow:
# Initialize model m = Model() # Define variables @variable(m, x >= 0) @variable(m, y >= 0) # Add constraints (including a "constraint 2" equivalent) @constraint(m, x + y <= 10) # Constraint 1 @constraint(m, 2x + y >= 5) # Constraint 2 - uses the model m correctly
If you fix the m variable to be the JuMP model instead of an integer, that error should vanish.
内容的提问来源于stack exchange,提问作者bhawesh sah

