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
@@ -65,7 +67,7 @@ std::vector<double> back_substitution(const std::vector<double>& a, int cols) {
65
67
soln[rows - 1 ] =
66
68
a[cols - 1 + (rows - 1 ) * cols] / a[cols - 1 - 1 + (rows - 1 ) * cols];
67
69
68
- for (int i = rows - 1 ; i >= 0 ; --i) {
70
+ for (int i = rows - 2 ; i >= 0 ; --i) {
69
71
auto sum = 0.0 ;
70
72
for (int j = cols - 2 ; j > i; --j) {
71
73
sum += soln[j] * a[j + i * cols];
@@ -86,7 +88,7 @@ void gauss_jordan_elimination(std::vector<double>& a, int cols) {
86
88
if (a[col + row * cols] != 0 ) {
87
89
88
90
// divide row by pivot and leaving pivot as 1
89
- for (int i = cols - 1 ; i >= static_cast < int >( col) ; --i)
91
+ for (int i = cols - 1 ; i >= col; --i)
90
92
a[i + row * cols] /= a[col + row * cols];
91
93
92
94
// subtract value from above row and set values above pivot to 0
@@ -104,16 +106,22 @@ void print_matrix(const std::vector<double>& a, int cols) {
104
106
for (int i = 0 ; i < rows; ++i) {
105
107
std::cout << " [" ;
106
108
for (int j = 0 ; j < cols; ++j) {
107
- std::cout << a[j + i * cols] << " " ;
109
+ std::cout << std::fixed << a[j + i * cols] << " \t " ;
108
110
}
109
111
std::cout << " ]\n " ;
110
112
}
111
113
}
112
114
113
115
int main () {
114
- std::vector<double > a = {2 , 3 , 4 , 6 , 1 , 2 , 3 , 4 , 3 , -4 , 0 , 10 };
116
+ std::vector<double > a = { 2 , 3 , 4 , 6 ,
117
+ 1 , 2 , 3 , 4 ,
118
+ 3 , -4 , 0 , 10 };
115
119
const int cols = 4 ;
116
- assert (a.size () % cols == 0 );
120
+ if (a.size () % cols != 0 )
121
+ {
122
+ std::cout << " The input dimentions are incorrect\n " ;
123
+ return 1 ;
124
+ }
117
125
118
126
gaussian_elimination (a, cols);
119
127
print_matrix (a, cols);
0 commit comments