-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGauss_Jordan_Matrix_Inversion_Parallelized.cpp
More file actions
111 lines (93 loc) · 2.48 KB
/
Gauss_Jordan_Matrix_Inversion_Parallelized.cpp
File metadata and controls
111 lines (93 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include <vector>
#include <cmath>
#include <omp.h>
using namespace std;
void printMatrix(const vector<vector<double>> &matrix)
{
for (int i = 0; i < matrix.size(); ++i)
{
for (double elem : matrix[i])
{
cout << elem << " ";
}
cout << endl;
}
cout << endl;
}
vector<vector<double>> gaussJordanInverse(const vector<vector<double>> &matrix)
{
int n = matrix.size();
vector<vector<double>> augmented(n, vector<double>(2 * n, 0.0));
#pragma omp parallel for schedule(static)
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
augmented[i][j] = matrix[i][j];
}
augmented[i][i + n] = 1.0;
}
for (int i = 0; i < n; i++)
{
int pivot = i;
for (int j = i + 1; j < n; j++)
{
if (fabs(augmented[j][i]) > fabs(augmented[pivot][i]))
{
pivot = j;
}
}
if (pivot != i)
{
swap(augmented[i], augmented[pivot]);
}
double pivotValue = augmented[i][i];
#pragma omp parallel for schedule(static)
for (int j = 0; j < 2 * n; j++)
{
augmented[i][j] /= pivotValue;
}
#pragma omp parallel for schedule(static)
for (int j = 0; j < n; j++)
{
if (j != i)
{
double factor = augmented[j][i];
for (int k = 0; k < 2 * n; k++)
{
augmented[j][k] -= factor * augmented[i][k];
}
}
}
}
vector<vector<double>> inverse(n, vector<double>(n));
#pragma omp parallel for schedule(static)
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
inverse[i][j] = augmented[i][j + n];
}
}
return inverse;
}
int main()
{
int n;
cin >> n;
vector<vector<double>> matrix(n, vector<double>(n));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> matrix[i][j];
}
}
double start_time = omp_get_wtime();
vector<vector<double>> inverse = gaussJordanInverse(matrix);
double end_time = omp_get_wtime();
cout << "Execution time: " << end_time - start_time << " seconds" << endl;
printMatrix(inverse);
return 0;
}