单纯形法单纯形法Python实现实现(一一)
1 介绍介绍
本文所提供的单纯形法Python实现,基于sympy和numpy库。使用时请先安装相关库。
优点:可以直接按目标函数和不等式约束的原形式输入。
缺点(BUG):
所有变量必须>=0
未解决约束条件全为等式情况
注意:对于等式约束,如x1+x2=5 x_1 + x_2 = 5 x1+x2=5 其代码输入格式为c0 = (x1+x2, 5)
2 安装相关库安装相关库
pip install numpy
pip install sympy
3 单纯形法单纯形法Python实现实现
simplex.py 代码内容参见 我的上传(点这里),代码测试后上传,没得错误~
4 算例算例
from sympy import *
from simplex import *
def example_0():
x1, x2, x3 = symbols('x1, x2, x3')
obj = -3 * x1 + x2 + x3
variables = [x1, x2, x3]
c0 = -4 * x1 + x2 + 2 * x3 >= 3
c1 = x1 - 2 * x2 + x3 X=', simplex.optimal_X)
print('==> y=', simplex.optimal_y)
def example_1():
x1, x2 = symbols('x1, x2')
obj = -(2*x1 + 3*x2)
variables = [x1, x2]
c0 = x1 + 2*x2 <= 8
c1 = 4*x1 <= 16
c2 = 4*x2 X=', simplex.optimal_X)
print('==> y=', -simplex.optimal_y)
def example_2():
# X=[21/5, 6/5], min_f=-18
x1, x2 = symbols('x1, x2')
obj = -4*x1 - x2
variables = [x1, x2]
c0 = -x1 + 2*x2 <= 4
c1 = 2*x1 + 3*x2 <= 12
c2 = x1 - x2 X=', simplex.optimal_X)
print('==> y=', simplex.optimal_y)
def example_3():
x1, x2, x3, x4, x5 = symbols('x1, x2, x3, x4, x5')
obj = 2*x1 + 3*x2 + 5*x3 + 2*x4 + 3*x5
variables = [x1, x2, x3, x4, x5]
c0 = x1 + x2 + 2*x3 + x4 + 3*x5 >= 4
c1 = 2*x1 - x2 + 3*x3 + x4 + x5 >= 3
constrs = [c0, c1] constrs_com = [GEQ, GEQ]
simplex = Simplex(obj, variables, constrs, constrs_com)
评论3
最新资源