这类问题属于所谓的“线性规划”。对于像您这样的简单系统,您通常可以通过手动分析和一张纸找到解决方案。但是,如果您有许多变量和许多约束,这将变得非常困难。由于求解线性规划非常有用,因此已经实现了许多简化任务的“求解器”。
您只需说明变量,即您允许它们采用的范围。然后是必须观察的约束,最后是您希望最小化或最大化的目标函数。
然后“点击”解决,瞧。即使对于大型实例,它通常也非常非常快。
(这是一个完整的领域,所以这只是一个简单的介绍)
>
这是一个使用库 ortools(来自 Google 的 OR-Tools)解决问题的示例:
import ortools
from ortools.linear_solver import pywraplp
solver = pywraplp.Solver('LinearProgrammingExample',
pywraplp.Solver.GLOP_LINEAR_PROGRAMMING)
x = solver.NumVar(0, 1, 'x')
y = solver.NumVar(0, 1, 'y')
constraint1 = solver.Constraint(0, solver.infinity())
constraint1.SetCoefficient(x, -1)
constraint1.SetCoefficient(y, 1)
# if you want to add another constraint like x+y = 1
# constraint2 = solver.Constraint(1, 1)
# constraint2.SetCoefficient(x, 1)
# constraint2.SetCoefficient(y, 1)
#
objective = solver.Objective()
objective.SetCoefficient(x, 10)
objective.SetCoefficient(y, 20)
objective.SetMaximization()
solver.Solve()
opt_solution = 10 * x.solution_value() + 20 * y.solution_value()
print('Solution:')
print('x = ', x.solution_value())
print('y = ', y.solution_value())
# The objective value of the solution.
print('Optimal objective value =', opt_solution)