求解线性方程组和线性不等式

ran*_*231 3 python numpy sympy inequalities

我必须获得线性表达式的最小和最大 y,受 python 中一些线性不等式的限制。

你可以在这里看到我在 Desmos 中输入的方程和不等式:

3x+12y = 1000
x > 30
x < 160
y < 60
y > 10
x + y > 180
Run Code Online (Sandbox Code Playgroud)

Desmos 方程 + 不等式

我可以通过绘制和删除不等式来手动解决它们。但我不能在 Python 中做到这一点。到目前为止,我在 Python 中尝试过的是在 x=0 时得到 y=83.33;当 y=0 时 x=333.33;在得到最小和最大 x,y 之后,我将不等式 1 x 1 应用。但是对于每一个不等式,我都必须添加之前的不等式,并且还要检查 x 或 y 是否已经超过了某个范围,到目前为止,它几乎是我肯定会错过支票。

我看着 numpy 和 sympy,但无法弄清楚如何使用它们来解决这个问题。您能否建议我使用什么/如何才能获得图片上白色箭头显示的范围?

Ror*_*ton 8

你的问题是线性规划中的一个问题,你的等式和不等式是限制,你想最小化(然后最大化)表达式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
Run Code Online (Sandbox Code Playgroud)

该代码的打印输出是

Minimum value of y = 43.3333333333
Maximum value of y = 51.1111111111
Run Code Online (Sandbox Code Playgroud)

这在浮点精度范围内是正确的。如果您需要 的相应值x,请参阅其中的值res.x是一个数组,该数组给出了xy在所需点的值- xisres.x[0]yis res.x[1]