diff --git a/README.md b/README.md index c338c5f..c9f9f3e 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,13 @@ # SimplexMethod +Команда: Заргаров Марат, Сергунов Максим + +Найти оптимальное решение симплекс методом: +f(x) = 2x1 + 3x2 -> max + +Ограничения: +x1 + 3x2 <= 18 +2x1 + x2 <= 16 +x2 <= 5 +3x1 <= 21 +x1,x2 >= 0 diff --git a/SimplexMethod.py b/SimplexMethod.py new file mode 100644 index 0000000..dfd50cf --- /dev/null +++ b/SimplexMethod.py @@ -0,0 +1,86 @@ +import numpy as np +import math + +class Simplex: + def __init__(self, source): + self.m, self.n = source.shape + self.table = np.zeros((self.m, self.n + self.m - 1)) + self.basis = [] + + for i in range(self.m): + for j in range(self.n): + self.table[i, j] = source[i, j] + + if (self.n + i) < self.table.shape[1]: + self.table[i, self.n + i] = 1 + self.basis.append(self.n + i) + + self.n = self.table.shape[1] + + def calculate(self, result): + while not self.is_it_end(): + main_col = self.find_main_col() + main_row = self.find_main_row(main_col) + self.basis[main_row] = main_col + + new_table = np.zeros((self.m, self.n)) + + for j in range(self.n): + new_table[main_row, j] = self.table[main_row, j] / self.table[main_row, main_col] + + for i in range(self.m): + if i == main_row: + continue + + for j in range(self.n): + new_table[i, j] = self.table[i, j] - self.table[i, main_col] * new_table[main_row, j] + + self.table = new_table + + for i in range(len(result)): + k = self.basis.index(i + 1) if i + 1 in self.basis else None + if k != None: + result[i] = self.table[k, 0] + else: + result[i] = 0 + + return self.table + + def is_it_end(self): + return all(self.table[self.m - 1, 1:] >= 0) + + def find_main_col(self): + return np.argmin(self.table[self.m - 1, 1:]) + 1 + + def find_main_row(self, main_col): + main_row = 0 + for i in range(self.m - 1): + if self.table[i, main_col] > 0: + main_row = i + break + for i in range(main_row + 1, self.m - 1): + if (self.table[i, main_col] > 0) and ((self.table[i, 0] / self.table[i, main_col]) < (self.table[main_row, 0] / self.table[main_row, main_col])): + main_row = i + + return main_row + +if __name__ == "__main__": + table = np.array([[18, 1, 3], + [16, 2, 1], + [5, 0, 0], + [21, 3, 0], + [0, -2, -3]]) + + result = np.zeros(2) + table_result = Simplex(table).calculate(result) + + print("Оптимальная таблица:") + for i in range(table_result.shape[0]): + for j in range(table_result.shape[1]): + print("%5.2f " % table_result[i][j], end='') + print() + + print("\nРешение:") + print(f"x1 = {result[0]}") + print(f"x2 = {math.ceil(result[1])}") + print(f"max = {-table[-1][-2] * result[0] + -table[-1][-1] * math.ceil(result[1])}") \ No newline at end of file