该函数接受目标函数的系数、约束矩阵、约束的右侧值、约束的方向和LP问题的类型然后,它使用lpSolveAPI包来创建LP问题,设置问题类型、决策变量类型和约束,然后求解LP问题。该函数返回包含最优解和目标函数值的列表,其可由用户访问。然后调用函数与特定的输入和最佳解决方案和目标函数值打印所有似乎是正确的,但我有sm问题时,它来到
下面是我函数:
solve_lp <- function(objective_coefs, constraints_matrix, constraints_rhs, constraints_dir, problem_type) {
# Load the lpSolveAPI package
library(lpSolveAPI)
# Set the number of rows (constraints) and columns (decision variables)
nrow <- nrow(constraints_matrix)
ncol <- ncol(constraints_matrix)
# Create an LP problem with nrow constraints and ncol decision variables
lprec <- make.lp(nrow = nrow, ncol = ncol)
# Set the type of problem to minimize or maximize the objective function based on the problem_type argument
lp.control(lprec, sense=problem_type)
# Set the type of decision variables to integer
set.type(lprec, 1:ncol, type=c("integer"))
# Set the objective function coefficients
set.objfn(lprec, objective_coefs)
# Add the constraints to the LP problem
for (i in 1:nrow) {
add.constraint(lprec, constraints_matrix[i, ], constraints_dir[i], constraints_rhs[i])
}
# Solve the LP problem
solve(lprec)
# If the problem has a feasible solution, get the decision variables values and the value of the objective function
solution <- get.variables(lprec)
obj_value <- get.objective(lprec)
# Return the optimal solution and objective function value
return(list(solution = solution, obj_value = obj_value))
}
objective_coefs <- c(15, 3, -6)
constraints_matrix <- matrix(c(1, 1, 1,
2, -1, -2,
2, 3, -5), nrow=3, byrow=TRUE)
constraints_rhs <- c(36, 8, 10)
constraints_dir <- c("<=", ">=", "=")
problem_type <- "min"
# Solve the LP problem using the solve_lp function
result <- solve_lp(objective_coefs = objective_coefs, constraints_matrix = constraints_matrix, constraints_rhs = constraints_rhs, constraints_dir = constraints_dir, problem_type= problem_type)
# Extract the optimal solution and objective function value
optimal_solution <- result$solution
obj_value <- result$obj_value
# Print the results
print(paste("Optimal solution:", optimal_solution))
print(paste("Objective function value:", obj_value))
min z = 15x1 + 3x2 − 6x3
S.C
x1 + x2 + x3 ≤ 36
2x1 − x2 − 2x3 ≥ 8
2x1 + 3x2 − 5x3 = 10
x1, x2, x3 ≥ 0
这个程序的结果输出变成了线性"Optimal solution: 5" "Optimal solution: 0" "Optimal solution: 0"
我测试了这个程序,从一个程序,我们在课堂上手动做,但我们有不同的输出7/14 0.5 0
我的问题是,哪一个解决方案是正确的
1条答案
按热度按时间oug3syen1#
使用lpSolve会更容易。res $solution给出解决方案。res $status为0表示成功。
给出:
注解
我们使用了以下输入: