Ubuntu 下 glpk 的安装及使用

时间:2024-06-24 09:04:32

作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4156204.html

glpk是一个开源的求解线性规划的包。

添加源:

deb http://us.archive.ubuntu.com/ubuntu saucy main universe

更新源并安装:

sudo apt-get update

sudo apt-get install glpk

写入如下glpsolEx.mod 文件

 /* Variables */
var x1 >= ;
var x2 >= ;
var x3 >= ; /* Object function */
maximize z: x1 + *x2 + *x3; /* Constrains */
s.t. con1: x1 + x2 + x3 <= ;
s.t. con2: x1 <= ;
s.t. con3: x3 <= ;
s.t. con4: *x2 + x3 <= ; end;

运行 glpsol -m glpsolEx.mod -o glpsolEx.sol,输出到glpsolEx.sol文件中

结果为:

 Problem:    glpsolEx
Rows:
Columns:
Non-zeros:
Status: OPTIMAL
Objective: z = (MAXimum) No. Row name St Activity Lower bound Upper bound Marginal
------ ------------ -- ------------- ------------- ------------- -------------
z B
con1 NU
con2 B
con3 B
con4 NU No. Column name St Activity Lower bound Upper bound Marginal
------ ------------ -- ------------- ------------- ------------- -------------
x1 NL -
x2 B
x3 B Karush-Kuhn-Tucker optimality conditions: KKT.PE: max.abs.err = 0.00e+00 on row
max.rel.err = 0.00e+00 on row
High quality KKT.PB: max.abs.err = 4.44e-16 on row
max.rel.err = 1.11e-16 on row
High quality KKT.DE: max.abs.err = 0.00e+00 on column
max.rel.err = 0.00e+00 on column
High quality KKT.DB: max.abs.err = 0.00e+00 on row
max.rel.err = 0.00e+00 on row
High quality End of output

帮助文档中一个求解八皇后的例子:

 /* QUEENS, a classic combinatorial optimization problem */

 /* Written in GNU MathProg by Andrew Makhorin <mao@gnu.org> */

 /* The Queens Problem is to place as many queens as possible on the 8x8
(or more generally, nxn) chess board in a way that they do not fight
each other. This problem is probably as old as the chess game itself,
and thus its origin is not known, but it is known that Gauss studied
this problem. */ param n, integer, > , default ;
/* size of the chess board */ var x{..n, ..n}, binary;
/* x[i,j] = 1 means that a queen is placed in square [i,j] */ s.t. a{i in ..n}: sum{j in ..n} x[i,j] <= ;
/* at most one queen can be placed in each row */ s.t. b{j in ..n}: sum{i in ..n} x[i,j] <= ;
/* at most one queen can be placed in each column */ s.t. c{k in -n..n-}: sum{i in ..n, j in ..n: i-j == k} x[i,j] <= ;
/* at most one queen can be placed in each "\"-diagonal */ s.t. d{k in ..n+n-}: sum{i in ..n, j in ..n: i+j == k} x[i,j] <= ;
/* at most one queen can be placed in each "/"-diagonal */ maximize obj: sum{i in ..n, j in ..n} x[i,j];
/* objective is to place as many queens as possible */ /* solve the problem */
solve; /* and print its optimal solution */
for {i in ..n}
{ for {j in ..n} printf " %s", if x[i,j] then "Q" else ".";
printf("\n");
} end;