我需要为线性规划问题实现一个求解器。所有的限制都是 <= 的,例如
5x + 10y <= 10
可以有任意数量的这些限制。此外,x>=0 y>=0 隐式。
我需要找到最优解(最大值)并在 matplotlib 中显示可行区域。我通过实现单纯形方法找到了最佳解决方案,但我不知道如何绘制图形。
我发现的一些方法:
最佳答案
一种更简单的方法可能是让 matplotlib 自己计算可行区域(您只提供约束),然后简单地将“约束”线叠加在顶部。
# plot the feasible region
d = np.linspace(-2,16,300)
x,y = np.meshgrid(d,d)
plt.imshow( ((y>=2) & (2*y<=25-x) & (4*y>=2*x-8) & (y<=2*x-5)).astype(int) ,
extent=(x.min(),x.max(),y.min(),y.max()),origin="lower", cmap="Greys", alpha = 0.3);
# plot the lines defining the constraints
x = np.linspace(0, 16, 2000)
# y >= 2
y1 = (x*0) + 2
# 2y <= 25 - x
y2 = (25-x)/2.0
# 4y >= 2x - 8
y3 = (2*x-8)/4.0
# y <= 2x - 5
y4 = 2 * x -5
# Make plot
plt.plot(x, 2*np.ones_like(y1))
plt.plot(x, y2, label=r'$2y\leq25-x$')
plt.plot(x, y3, label=r'$4y\geq 2x - 8$')
plt.plot(x, y4, label=r'$y\leq 2x-5$')
plt.xlim(0,16)
plt.ylim(0,11)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
关于python-3.x - 如何在 Numpy/MatplotLib 中可视化线性规划(具有任意不等式)的可行区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57017444/