R语言做简单线性规划

首先要安装线性规划扩展包

install.packages("lpSolve")

例1:
某工厂甲、乙两种产品,每件甲产品要耗钢材2kg、煤2kg、产值为120元;每件乙产品要耗钢材3kg,煤1kg,产值为100元。现钢厂有钢材600kg,煤400kg,试确定甲、乙两种产品各生产多少件,才能使该厂的总产值最大?

解:

# 优化方向: 
# maximize
# 目标函数:
# f(X1,X2)=120X1+100X2
# 约束条件:
# 2X1+3X2<=600
# X1+X2<=400

#引用lpSolve
library (lpSolve)

#求解
f.obj <- c (120, 100)
f.con <- matrix ( c (2, 3, 1, 1), nrow = 2, byrow = TRUE )
f.dir <- c ( "<=" , "<=" )
f.rhs <- c (600, 400)
lp.result <- lp ( "max" , f.obj, f.con, f.dir, f.rhs)

#输出结果
lp.result
#Success: the objective function is 36000 

#输出解
lp.result$solution
#[1] 300   0

例2:
某工厂要做100套钢架,每套用长为2.9m,2.1m,1.5m的圆钢各一根。已知原料每根长7.4m,问:应如何下料,可使所用原料最省?(可选方案如下)

可选方案 方案1 方案2 方案3 方案4 方案5
2.9m 1 2 0 1 0
2.1m 0 0 2 2 1
1.5m 3 1 2 0 3
合计 7.4 7.3 7.2 7.1 6.6
剩余料头 0 0.1 0.2 0.3 0.8

解:

# 优化方向: 
# minimize
# 目标函数:
# f(X1,X2,X3,X4,X5)=0X1+0.1X2+0.2X3+0.3X4+0.8X5
# 约束条件:
# X1+2X2 + 0X3 + X4 + 0X5>=100
# 0X1+0X2 + 2X3 + 2X4 + 1X5>=100
# 3X1+X2 + 2X3 + 0X4 + 3X5>=100

#引用lpSolve
library (lpSolve)

#求解
f.obj <- c (0, 0.1, 0.2, 0.3, 0.8)
f.con <- matrix ( c (1, 2, 0, 1, 0, 0, 0, 2, 2, 1, 3, 1, 2, 0, 3), nrow = 3, byrow = TRUE )
f.dir <- c ( ">=", ">=", ">=" )
f.rhs <- c (100, 100, 100)
lp.result <- lp ( "min" , f.obj, f.con, f.dir, f.rhs)

#输出结果
lp.result
#Success: the objective function is 10

#输出解
lp.result$solution
#[1] 100   0  50   0   0

Leave a Reply

Your email address will not be published. Required fields are marked *

*