R中的线性编程:一家汽车公司生产3种模型

时间:2019-07-18 02:05:45

标签: r linear-programming lpsolve

一家汽车公司生产3种模型,即A / B / C模型。长期预测表明,每天预计至少需要100辆A型汽车,80辆B型汽车和120辆C型汽车。由于生产能力的限制,每天最多只能生产200辆A型汽车,170辆B型汽车和150辆C型汽车。为了满足运输合同,每天总共要运送至少300辆汽车。如果售出的每辆A型汽车造成1500美元的损失,但每辆B型汽车产生3800美元的利润,每辆C型汽车产生2500美元的利润,那么每种类型的汽车每天应该赚多少以实现净利润最大化?

到目前为止,我在R中使用lpSolve。请参见下面的代码。

library(lpSolve) #Loading lpSolve library
obj.fun=c(-1500,3800,2500) #Loading the objective function in obj.fun

constr <- matrix(c(1,0,1,0,0,1,0,1,1,1), ncol=3, byrow=TRUE) #Loading the constraints constr.dir=c(">=","<=",">=","<=",">=", "<=",">=") constr.rhs=c(100,200,80,170,120,150,300) mod=lp("max",obj.fun,constr,constr.dir,constr.rhs,compute.sens = TRUE)

使用lp()解决我们的问题

mod$solution #Displaying the values of x, y.c y=170 C=200 z = (3800*y)-(2500*x) #Putting the values of x and y in the objective function options("scipen"=200, "digits"=4) cat("Net profit =", z) #Displaying the maximum profit

运行第一行代码后,收到以下消息:

data length [10] is not a sub-multiple or multiple of the number of rows [4]number of columns of result is not a multiple of vector length (arg 2)[1] 0 170 200

然后运行第二个代码,并获得446000的净利润。

不确定这些是否正确。我想我知道如何用两种型号的汽车来解决这个问题,但不明白如何用三种型号的A / B / C来解决这个问题。

1 个答案:

答案 0 :(得分:0)

我不建议您尝试使用R解决此问题。与Python和Julia所提供的软件包相比,其用于优化的软件包是原始的,这就是使用正确的工具可以使您的生活< em>容易。

Julia的JuMP是我最推荐使用的工具,但是我认为Python仍然是更强大的语言,因为它具有一套更完善,更实用的库来处理程序的其他部分。 cvxpy特别具有many advanced features,而这在任何其他工具中都无法提供。

我已使用下面的cvxpy重写了您的问题。请注意,与R版本相比,它更容易理解。

#!/usr/bin/env python3
import cvxpy as cp

A = cp.Variable(pos=True)
B = cp.Variable(pos=True)
C = cp.Variable(pos=True)

objective = cp.Maximize(-1500*A+3800*B+2500*C)

constraints = [
  A<=200,
  B<=170,
  C<=150,
  A+B+C==300
]

prob = cp.Problem(objective, constraints)

optimal_value = prob.solve()
print("Optimal value = {0}".format(optimal_value))
print("A.value = {0}".format(A.value))
print("B.value = {0}".format(B.value))
print("C.value = {0}".format(C.value))