Repository navigation
Expand file tree
/
Copy pathmatrix_solve.cpp
More file actions
110 lines (80 loc) · 1.72 KB
/
Copy pathmatrix_solve.cpp
File metadata and controls
110 lines (80 loc) · 1.72 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
#include "matrix_solve.hpp"
void Matrix::create(int size)
{
this->size = size;
data = new double *[size];
for(int i = 0; i < size; i++){
data[i] = new double[size];
}
}
void Matrix::clear()
{
if(data)
{
for(int i = 0; i < size; i++){
delete[] data[i];
}
delete[] data;
}
}
int Matrix::findMaxAbsElementRow(int n)
{
double tmp;
double max = fabs(data[n][n]);
int res = n;
for(int i = n + 1; i < size; i++){
tmp = fabs(data[i][n]);
if(tmp > max){
res = i;
max = tmp;
}
}
return res;
}
/*
* Makes one gauss forward step (for the n-th string).
*/
void gaussStep(Matrix &A, double *f, int n)
{
double m;
double w = A(n, n);
for(int i = n + 1; i < A.getSize(); i++){
m = A(i, n) / w;
for(int j = n + 1; j < A.getSize(); j++){
A(i, j) -= m * A(n, j);
}
f[i] -= m * f[n];
A(i, n) = 0.0;
}
}
/*
* Performs reverse Gauss calculation.
*/
double *reverseGauss(const Matrix &A, double *f)
{
double hlp;
double *x = new double[A.getSize()];
for(int i = A.getSize() - 1; i >= 0; i--){
hlp = 0.0;
for(int j = A.getSize() - 1; j > i; j--){
hlp += A(i, j) * x[j];
}
x[i] = (f[i] - hlp) / A(i, i);
}
return x;
}
double *solveGauss(Matrix &A, double *f)
{
int m_row;
for(int i = 0; i < A.getSize() - 1; i++){
m_row = A.findMaxAbsElementRow(i);
if(m_row != i){
A.swapRows(i, m_row);
}
# ifndef DASCETIC
printf("%d/%d\n", i, A.getSize());
# endif
gaussStep(A, f, i);
}
return reverseGauss(A, f);
}