ABS() 在 PuLP 的目标函数中的数学运算.



我正在尝试在PuLP中构建一个LP问题,因为我是python的新手,所以想知道如何使用绝对值的操作编写目标函数。

到目前为止,我一直使用 AMPL 进行问题表述,现在想将整个模型转换为 Python。谁能帮助我了解如何编码

SUM(ABS(x)) in objective function of PulP
x is the decision variable which is output of the model and objective function of the model is SUM(ABS(x))
from pulp import *
N = 3
x_vars = LpVariable.dicts("x",range(N))
x_vars_abs = LpVariable.dicts("x_abs",range(N))
prob = LpProblem("min_sum_abs", LpMinimize)
# OBJECTIVE
prob += lpSum(x_vars_abs)
# ABS CONSTRAINTS
for i in range(N):
prob += x_vars_abs[i] >= x_vars[i]
prob += x_vars_abs[i] >= -x_vars[i]
# OTHER MODEL CONSTRAINTS
prob += lpSum(x_vars) >= 2.0
prob += x_vars[0] >= x_vars[1] + 1.0
prob += x_vars[1] <= x_vars[2] - 2.0
prob.solve()
print ("Status: " + str(LpStatus[prob.status]))
print ("Objective: " + str(value(prob.objective)))
for v in prob.variables():
print (v.name + " = " + str(v.varValue))

返回:

Status: Optimal
Objective: 2.6666667
x_0 = 0.66666667
x_1 = -0.33333333
x_2 = 1.6666667
x_abs_0 = 0.66666667
x_abs_1 = 0.33333333
x_abs_2 = 1.6666667

最新更新