金融量化学习---Python, MySQL, Pandas

这里用来记录一些在金融领域,尤其是银行相关的资金、债券、票据中应用到的数据管理与分析, 编程等心得或笔记,以及个人的一点小小兴趣(易经八卦、藏密禅修)等

导航

Pulp之四:其它应用样例(1)-一般的整数规划问题 (设置目标约束函数)

解如下整数线性规划
maximize z = cx = 3x1 + 4x2 + 5x3
subject to :
x1 2 3 >= 0
x1 + 2x2 < 20
x2 + 3
x3 <= 40

import pulp as pulp

def solve_ilp(objective , constraints) :
    print(objective)
    print(constraints)
    prob = pulp.LpProblem('LP1' , pulp.LpMaximize)
    prob += objective
    for cons in constraints :
        prob += cons
    print(prob)
    status = prob.solve()
    if status != 1 :
        return None
    else :
        return [v.varValue.real for v in prob.variables()]
V_NUM = 3
#变量,直接设置下限,约束条件中的不等式只支持>=或<=,不支持<和>
#如果是解线性规划只需要在生成变量时cat = pulp.LpContinuous
variables = [pulp.LpVariable('X%d'%i , lowBound = 0 , cat = pulp.LpInteger) for i in range(0 , V_NUM)]
#目标函数
c = [3 , 4 , 5]
objective = sum([c[i]*variables[i] for i in range(0 , V_NUM)])
#约束条件
constraints = []

a1 = [1 , 2 , 0]
constraints.append(sum([a1[i]*variables[i] for i in range(0 , V_NUM)]) <= 20)
a2 = [0 , 1 , 3]
constraints.append(sum([a2[i]*variables[i] for i in range(0 , V_NUM)]) <= 40)
print(constraints)

res = solve_ilp(objective , constraints)
print(res)

运行结果:

posted on 2020-10-12 00:04  chengjon  阅读(385)  评论(0编辑  收藏  举报