diff --git a/antonov_dmitry_lab_6/parallel_determ.py b/antonov_dmitry_lab_6/parallel_determ.py new file mode 100644 index 0000000..2204f96 --- /dev/null +++ b/antonov_dmitry_lab_6/parallel_determ.py @@ -0,0 +1,70 @@ +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) + + # Base case: determinant of a 1x1 matrix is the only element in it + if size == 1: + return matrix[0][0] + + # Base case: determinant of a 2x2 matrix + 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"Sequential determinant: {result}") + print(f"Sequential time: {end_time - start_time} seconds") + + +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"Parallel determinant: {result}") + print(f"Parallel time: {end_time - start_time} seconds") + + +if __name__ == "__main__": + matrix_size = 10 # You can change this to the desired size of the matrix + lower_limit = 10 # You can change this to the lower limit of the random numbers + upper_limit = 1000 # You can change this to the upper limit of the random numbers + num_processes = 8 # You can change this to the desired number of parallel processes + + # Sequential calculation + sequential_determinant_calculation(matrix_size, lower_limit, upper_limit) + + # Parallel calculation + parallel_determinant_calculation(matrix_size, lower_limit, upper_limit, num_processes) +