你的问题是线性规划中的一个问题,你的等式和不等式是限制,你想最小化(然后最大化)表达式y
。等式、不等式和表达式都是线性的,所以它是线性规划。scipy
使用该函数的包可以scipy.optimize.linprog
进行这种线性规划。
这是注释代码来做你想做的事。请注意,所有不等式都进行了轻微更改,以包括等式,这是具有最大值或最小值所必需的y
。为了找到代码的最大值,y
而不是找到最小值,-y
然后打印它的加法倒数,因为linprog
最小化了目标函数。最后,不等式限制必须在 中“小于或等于” linprog
,所以我将你的不等式两边乘以x + y > 180
得到-1
一个,即-x + -y <= -180
。询问您是否有任何问题。
from scipy.optimize import linprog
# Set up values relating to both minimum and maximum values of y
coefficients_inequalities = [[-1, -1]] # require -1*x + -1*y <= -180
constants_inequalities = [-180]
coefficients_equalities = [[3, 12]] # require 3*x + 12*y = 1000
constants_equalities = [1000]
bounds_x = (30, 160) # require 30 <= x <= 160
bounds_y = (10, 60) # require 10 <= y <= 60
# Find and print the minimal value of y
coefficients_min_y = [0, 1] # minimize 0*x + 1*y
res = linprog(coefficients_min_y,
A_ub=coefficients_inequalities,
b_ub=constants_inequalities,
A_eq=coefficients_equalities,
b_eq=constants_equalities,
bounds=(bounds_x, bounds_y))
print('Minimum value of y =', res.fun)
# Find and print the maximal value of y = minimal value of -y
coefficients_max_y = [0, -1] # minimize 0*x + -1*y
res = linprog(coefficients_max_y,
A_ub=coefficients_inequalities,
b_ub=constants_inequalities,
A_eq=coefficients_equalities,
b_eq=constants_equalities,
bounds=(bounds_x, bounds_y))
print('Maximum value of y =', -res.fun) # opposite of value of -y
该代码的打印输出是
Minimum value of y = 43.3333333333
Maximum value of y = 51.1111111111
在浮点精度范围内是正确的。如果您需要 的相应值x
,请查看 的值res.x
是一个数组,该数组给出了所需点的x
和的值-- is和is 。y
x
res.x[0]
y
res.x[1]