简体   繁体   English

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

[英]Mathematical operation of ABS() in objective function of PuLP

I am trying to build a LP problem in PuLP and since I am new to python, wanted to know how to write the objective function with the operation of absolute values.我正在尝试在 PuLP 中构建 LP 问题,并且由于我是 Python 新手,想知道如何使用绝对值运算来编写目标函数。

Till now I was using AMPL for my problem formulation and now want to convert the whole model to Python.到目前为止,我一直在使用 AMPL 来解决问题,现在想将整个模型转换为 Python。 Can anyone help me understand how to code谁能帮我理解如何编码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM