你的问题是线性规划中的问题,你的等式和不等式是限制,你想最小化(然后最大化)表达式y。等式、不等式和表达式都是线性的,所以它是线性规划。使用scipy函数的scipy包可以进行这种线性规划。在
这里是注释代码,可以做你想做的。注意,所有的不等式都稍加修改以包含等式,这对于具有最大或最小值y是必要的。为了找到y的最大值,代码转而找到-y的最小值,然后打印该值的加法逆,因为{}最小化了目标函数。最后,不等式限制必须是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
该代码的打印输出是
^{2}$
在浮点精度范围内是正确的。如果您需要x的对应值,请参见res.x的值,它是一个数组,它在所需的点x和{}的值都是res.x[0],而{}是{}。在