-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gauss.cpp
100 lines (84 loc) · 1.98 KB
/
Gauss.cpp
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
#include <bits/stdc++.h>
#define Col 3
#define Row 3
#define FOR(i,a,b) for(long long i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define debug(x) cout << #x << " = " << x << endl;
using namespace std;
//double a[Col][Row] = {{2.0,3.0,3.0},{3.0,2.0,-1.0},{5.0,4.0,2.0}};
//double a[Col][Row] = {{5.0, 1.0, 0.0},{1.0, 3.0, 1.0},{0.0, 1.0, 4.0}};
double a[Col][Row] = {{0.0,1.0,-1.0},{1.0,0.0,-1.0},{1.0,1.0,0.0}};
//double b[Col] = {5.0,-4.0,3.0};
//double b[Col] = {7.0,10.0,14.0};
double b[Col] = {2.0,0.0,1.0};
void pivotSelect(){
double p;
double pMax;
REP(k,Col){
p = k;
pMax = fabs(a[k][k]);
FOR(i,k+1,Col){
if(a[i][k] > pMax){
p = i;
pMax = fabs(a[i][k]);
}
}
if((int)p != k){
FOR(i,k,Col){
swap(a[k][i],a[(int)p][i]);
}
swap(b[k],b[(int)p]);
}
}
}
void gaussElimination(){
REP(k,Col){
FOR(i,k+1,Col){
double tmp = a[i][k] / a[k][k];
REP(j,Row){
a[i][j] -= tmp*a[k][j];
}
b[i] -= tmp*b[k];
}
}
}
void pGaussElimination(){
pivotSelect();
REP(k,Col){
FOR(i,k+1,Col){
double tmp = a[i][k] / a[k][k];
REP(j,Row){
a[i][j] -= tmp*a[k][j];
}
b[i] -= tmp*b[k];
}
}
}
void substBack(){
for(int i = Col-1; i >= 0; i --){
FOR(j,i+1,Row){
b[i] -= a[i][j] * b[j];
a[i][j] = 0.0;
}
b[i] /= a[i][i];
a[i][i] = 1.0;
}
}
void printMatrix(){
REP(i,Col){
REP(j,Row){
printf("\t%lf ",a[i][j]);
}
printf("\t%lf\n",b[i]);
}
printf("\n");
}
int main(){
printf("\tInitial Matrix\n\n");
printMatrix();
//pGaussElimination();
gaussElimination();
substBack();
printf("\tAnswer Matrix\n\n");
printMatrix();
}