3
3
#include < cmath>
4
4
#include < iostream>
5
5
#include < vector>
6
+ #include < iomanip>
6
7
7
8
void gaussian_elimination (std::vector<double >& a, int cols) {
8
9
assert (a.size () % cols == 0 );
@@ -16,11 +17,12 @@ void gaussian_elimination(std::vector<double>& a, int cols) {
16
17
int max_index = [&]() {
17
18
int res = row;
18
19
int max_element = a[col + row * cols];
19
- for (int r = row + 1 ; r < rows; ++r)
20
+ for (int r = row + 1 ; r < rows; ++r) {
20
21
if (max_element < std::abs (a[col + r * cols])) {
21
22
max_element = std::abs (a[col + r * cols]);
22
23
res = r;
23
24
}
25
+ }
24
26
return res;
25
27
}();
26
28
@@ -61,10 +63,6 @@ std::vector<double> back_substitution(const std::vector<double>& a, int cols) {
61
63
// Creating the solution Vector
62
64
std::vector<double > soln (rows);
63
65
64
- // initialize the final element
65
- soln[rows - 1 ] =
66
- a[cols - 1 + (rows - 1 ) * cols] / a[cols - 1 - 1 + (rows - 1 ) * cols];
67
-
68
66
for (int i = rows - 1 ; i >= 0 ; --i) {
69
67
auto sum = 0.0 ;
70
68
for (int j = cols - 2 ; j > i; --j) {
@@ -86,7 +84,7 @@ void gauss_jordan_elimination(std::vector<double>& a, int cols) {
86
84
if (a[col + row * cols] != 0 ) {
87
85
88
86
// divide row by pivot and leaving pivot as 1
89
- for (int i = cols - 1 ; i >= static_cast < int >( col) ; --i)
87
+ for (int i = cols - 1 ; i >= col; --i)
90
88
a[i + row * cols] /= a[col + row * cols];
91
89
92
90
// subtract value from above row and set values above pivot to 0
@@ -104,16 +102,22 @@ void print_matrix(const std::vector<double>& a, int cols) {
104
102
for (int i = 0 ; i < rows; ++i) {
105
103
std::cout << " [" ;
106
104
for (int j = 0 ; j < cols; ++j) {
107
- std::cout << a[j + i * cols] << " " ;
105
+ std::cout << std::fixed << a[j + i * cols] << " \t " ;
108
106
}
109
107
std::cout << " ]\n " ;
110
108
}
111
109
}
112
110
113
111
int main () {
114
- std::vector<double > a = {2 , 3 , 4 , 6 , 1 , 2 , 3 , 4 , 3 , -4 , 0 , 10 };
112
+ std::vector<double > a = { 2 , 3 , 4 , 6 ,
113
+ 1 , 2 , 3 , 4 ,
114
+ 3 , -4 , 0 , 10 };
115
115
const int cols = 4 ;
116
- assert (a.size () % cols == 0 );
116
+ if (a.size () % cols != 0 )
117
+ {
118
+ std::cout << " The input dimentions are incorrect\n " ;
119
+ return 1 ;
120
+ }
117
121
118
122
gaussian_elimination (a, cols);
119
123
print_matrix (a, cols);
0 commit comments