PuLP目标函数中ABS()的数学运算 [英] Mathematical operation of ABS() in objective function of PuLP

查看:117
本文介绍了PuLP目标函数中ABS()的数学运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PuLP中构建LP问题,由于我是python的新手,所以想知道如何使用绝对值的运算来编写目标函数.

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.

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

Till now I was using AMPL for my problem formulation and now want to convert the whole model to 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))

返回:

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

这篇关于PuLP目标函数中ABS()的数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆