Constraints + objective in one go.
Chapter: I — Foundations · lesson id two-vars-objective · practice lesson
Real models have multiple variables and constraints. Here we have two — x and y, both non-negative — and a single structural constraint x + y <= 5.
The objective coefficients tell the solver which variables it should care about. With max 1*x + 3*y, each unit of y is worth three times each unit of x. Given the budget x + y ≤ 5, the solver puts everything on y.
Try flipping max to min — the optimum jumps to the origin.
With max 1*x + 3*y and budget x + y <= 5, where does the solver put the budget?
model weighted
var 0 <= x
var 0 <= y
constr x + y <= 5
max 1*x + 3*y
end
import elytica
def main():
elytica.init_model("weighted")
elytica.run_model("weighted")
print("x =", elytica.get_variable_value("weighted", "x"))
print("y =", elytica.get_variable_value("weighted", "y"))
return 0
Predict the optimum before running. Whichever variable has the larger coefficient wins.
no-error — Model solvesnumeric-match — Solver leaves x at 0 (smaller coefficient)numeric-match — Solver pushes y to the budget (5)code-contains — Reads variable values from the solver (no hardcoding)Different budget, different coefficients. Predict which variable wins this time.
model weighted_v
var 0 <= a
var 0 <= b
constr 2*a + b <= 12
max 5*a + 2*b
end
import elytica
def main():
elytica.init_model("weighted_v")
elytica.run_model("weighted_v")
print("a =", elytica.get_variable_value("weighted_v", "a"))
print("b =", elytica.get_variable_value("weighted_v", "b"))
return 0
Read this through MCP: read with path: "lessons/two-vars-objective", or resource hlpl://lessons/two-vars-objective.