distributed-computing/tasks/plaksina-av/lab_6/determinant.py

71 lines
2.5 KiB
Python
Raw Permalink Normal View History

2023-12-17 00:55:54 +04:00
import random
from multiprocessing import Pool
import time
def submatrix(matrix, row, col):
return [[matrix[i][j] for j in range(len(matrix[i])) if j != col] for i in range(len(matrix)) if i != row]
def determinant(matrix):
size = len(matrix)
# Простой случай: детерминант матрицы 1x1
if size == 1:
return matrix[0][0]
# Простой случай: детерминант матрицы 2x2
if size == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for col in range(size):
det += ((-1) ** col) * matrix[0][col] * determinant(submatrix(matrix, 0, col))
return det
def generate_random_matrix(size, lower_limit, upper_limit):
return [[random.uniform(lower_limit, upper_limit) for _ in range(size)] for _ in range(size)]
def sequential_determinant_calculation(matrix_size, lower_limit, upper_limit):
random_matrix = generate_random_matrix(matrix_size, lower_limit, upper_limit)
start_time = time.time()
result = determinant(random_matrix)
end_time = time.time()
print(f"Последовательный детерминант: {result}")
print(f"Последовательное время: {end_time - start_time} секунд")
def parallel_determinant_calculation(matrix_size, lower_limit, upper_limit, num_processes):
random_matrix = generate_random_matrix(matrix_size, lower_limit, upper_limit)
matrices_to_process = [submatrix(random_matrix, 0, col) for col in range(matrix_size)]
start_time = time.time()
with Pool(processes=num_processes) as pool:
determinants = pool.map(determinant, matrices_to_process)
result = sum(((-1) ** col) * random_matrix[0][col] * det for col, det in enumerate(determinants))
end_time = time.time()
print(f"Параллельный детерминант: {result}")
print(f"Параллельное время: {end_time - start_time} секунд")
if __name__ == "__main__":
matrix_size = 10 # размер матрицы
lower_limit = 5 # числа в матрице от
upper_limit = 15 # и до
processes = [2, 4, 8, 16, 32]
#
# последовательное вычисление
#sequential_determinant_calculation(matrix_size, lower_limit, upper_limit)
# параллельное вычисление
for i in processes:
print("Потоков " + str(i))
parallel_determinant_calculation(matrix_size, lower_limit, upper_limit, i)