1. 使用工具 PULP+GLPK PULP 是 Python PULP 是用 python 写的建模描述语言, GLPK 是线性规划工具 2. 下载、安装 Python 、 PULP 和 GLPK 以 Python 2.7+PULP 1.4.8 +GLPK4.49 为例 Python 下载地址: http://www.python.org/getit/ GLPK 下载地址: http://www.lupaworld.com/proj-cont-id-121212.html PUPL 下载地址: http://www.coin-or.org/download/source/PuLP/ PUPL Windows 安装: 1. 解压下载好的文件(如解压到 C:\Python27 ) 2. 点击开始—运行 键入 cmd 进入命令行,键入 cd C:\Python27\PuLP-1.4.8 更改路径到 setup.py 所在的文件夹 3. 键入 setup.py install 安装 PUPL 4. 测试是否安装成功 import PULP pulp.pulpTestAll() GLPK 安装 1. 解压下载好的文件(如解压到 C:\glpk-4.49 ) 3. 求解过程 Formulate the Objective Function The objective function becomes: min 0:013x 1 + 0:008x 2 The Constraints The constraints on the variables are that they must sum to 100 and that the nutritional requirements are met: 1:000x 1 + 1:000x 2 = 100.0 0:100x 1 + 0:200x 2 = 8.0 0:080x 1 + 0:100x 2 =6.0 0:001x 1 + 0:005x 2 =2.0 0:002x 1 + 0:005x 2 =0.4 Solution to Simplified Problem from pulp import * ##Create the ’prob’ variable to contain the problem data prob = LpProblem("The Whiskas Problem",LpMinimize) x1=LpVariable("ChickenPercent",0,None,LpInteger) x2=LpVariable("BeefPercent",0,None, LpInteger) prob += 0.013*x1 + 0.008*x2 ## The five constraints are entered prob += x1 + x2 == 100 prob += 0.100*x1 + 0.200*x2 = 8.0 prob += 0.080*x1 + 0.100*x2 = 6.0 prob += 0.001*x1 + 0.005*x2 = 2.0 prob += 0.002*x1 + 0.005*x2 = 0.4 # The problem data is written to an .lp file prob.writeLP("WhiskasModel.lp") # The problem is solved using PuLP’s choice of Solver prob.solve(“C:\\glpk-4.49\\w32\\glpsol.exe”) # prob.solve() 也可以,或者将 C:\glpk-4.49\w32\glpsol.exe 加入到 path 用 #prob.solve(glpk()) # The status of the solution is printed to the screen print "Status:", LpStatus for v in prob.variables(): print v.name, "=", v.varValue print "Total Cost of Ingredients per can = ", value(prob.objective) -----------------------Result --------------------------------------- Status: Optimal ChickenPercent = 34.0 BeefPercent = 66.0 Total Cost of Ingredients per can = 0.97