R中的线性规划:一家汽车公司生产3种车型



一家汽车公司生产3款车型,型号A/B/C.长期预测表明,预计每天至少需要100辆A型车,80辆B型车和120辆C型车。由于生产能力的限制,每天只能生产200辆A型车和170辆B型车和150辆C型车。为了满足运输合同,每天至少要运输300辆汽车。如果每辆A型车卖出1500元亏损,但每辆B型车产生3800元利润,每辆C型车产生2500元利润,每种车型每天应该赚多少辆才能实现净利润最大化?

到目前为止,我正在使用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来解决这个问题。

我不建议您尝试使用 R 来解决此问题。与通过Python和Julia提供的软件包相比,它的优化包是原始的,这是使用正确的工具可以使您的生活更轻松的问题。

Julia 的 JuMP 是我最推荐使用的工具,但我认为 Python 仍然是更强大的语言,因为它有一套更完整、功能更强大的库来处理程序的其他部分。 特别是CVXPY具有许多其他工具所没有的高级功能。

我已经在下面使用 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))

相关内容

最新更新