线性规划标准形式:MATLAB
-------------
线性规划求解主要分 两个部分,目标函数(max,min)和约束条件(s.t.),求解时一般要化为MATLAB标准形式:
求解用到的模块(scipy 和 numpy):
from scipy import optimizeimport numpy as np
例题:
转换成标准系数格式:
c = [2, 3, -5]A = [[-2, 5, -1], [1, 3, 1]]b = [-10, 12]Aeq = [[1, 1, 1]]beq = [7]x1 = (0, None)x2 = (0, None)x3 = (0, None)
LP求解函数:
#-*- coding:utf-8 -*-#导入包from scipy import optimizeimport numpy as npdef LP(m='',clist=[],Alist=[],blist=[],Aeqlist=[],beqlist=[],all_x=()): #c,A,b,Aeq,beq,LB,UB,X0,OPTIONS c = np.array(clist) A = np.array(Alist) b = np.array(blist) Aeq = np.array(Aeqlist) beq = np.array(beqlist) #求解 if m == 'min': res = optimize.linprog(c, A, b, Aeq, beq, bounds=all_x) fun = res.fun x = res.x else: res = optimize.linprog(-c, A, b, Aeq, beq, bounds=all_x) fun = -(res.fun) x = res.x return fun,x
main函数,方便其它调用:
#-*- coding:utf-8 -*-import LPimport sysif __name__ == '__main__': m = sys.argv[1] clist = list(eval(sys.argv[2])) Alist = list(eval(sys.argv[3])) blist = list(eval(sys.argv[4])) Aeqlist = list(eval(sys.argv[5])) beqlist =list(eval(sys.argv[6])) all_x = tuple(eval(sys.argv[7])) r=LP.LP(m=m,clist=clist,Alist=Alist,blist=blist,Aeqlist=Aeqlist,beqlist=beqlist,all_x=all_x) print(r)
说明: (1)因为系统参数传入的都是字符串格式,所以main文件中,将传入参数都转换成列表。
(2)标准是最小值,如果是最大值,c应该换成-c
最后执行结果:
红圈里就是最大值,和最优解。
C#调用,参考:
https://blog.csdn.net/qq_42063091/article/details/82418630