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

2024-04-07

我正在尝试在 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))

Returns:

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PuLP目标函数中ABS()的数学运算 的相关文章

随机推荐