Gurobi / modeling-examples

Gurobi modeling examples
https://gurobi.github.io/modeling-examples/
Apache License 2.0
615 stars 272 forks source link

TypeError: must be real number, not Var #10

Closed StevenQiu1 closed 2 years ago

StevenQiu1 commented 2 years ago

My objective function is this

\mbox{Average Profit under }(s_1,s_2,...,s5)=\max \quad & \frac{1}{5}\sum{k=1}^5 \left(\sum{i=1}^m\sum{j=1}^n (12.25-c{ij})x{ij}^k\right)\

Here's what I wrote model.setObjective(quicksum((r-c[i,j]) * math.pow(x[i,j,k] ,k)for i in range(n) for j in range(m) for k in range(5)), GRB.MAXIMIZE)

Errors

-TypeError: must be real number, not Var

mattmilten commented 2 years ago

Hi Steven,

You cannot put the exponent directly into the objective. You need to add an auxiliary variable to hold that value and then put this into the objective:

xpow = model.addVars(n,m,5)
for k in range(5):
    for i in range(n):
        for j in range(m):
            model.addGenConstrPow(x[i,j,k], xpow[i,j,k], k)
model.setObjective(quicksum((r-c[i,j]) * xpow[i,j,k] for i in range(n) for j in range(m) for k in range(5)), GRB.MAXIMIZE)

You can read more about this constraint type here: Model.addGenConstrPow