-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathGaussian 2.cpp
53 lines (41 loc) · 1.11 KB
/
Gaussian 2.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
const double eps = 1e-9;
// *****may return empty vector
vector<double> gauss(vector<vector<double>> &a)
{
int n = a.size(), m = a[0].size() - 1;
vector<int> where(m, -1);
for(int col = 0, row = 0; col < m && row < n; col++)
{
int sel = row;
for(int i = row; i < n; i++)
if(abs(a[i][col]) > abs(a[sel][col]))
sel = i;
if(abs(a[sel][col]) < eps) { where[col] = -1; continue; }
for(int i = col; i <= m; i++)
swap(a[sel][i], a[row][i]);
where[col] = row;
for(int i = 0; i < n; i++)
if(i != row)
{
if(abs(a[i][col]) < eps) continue;
double c = a[i][col] / a[row][col];
for(int j = 0; j <= m; j++)
a[i][j] -= c * a[row][j];
}
row++;
}
vector<double> ans(m, 0);
for(int i = 0; i < m; i++)
if(where[i] != -1)
ans[i] = a[where[i]][m] / a[where[i]][i];
// Validity check?
// May need to remove the following code
for(int i = 0; i < n; i++)
{
double sum = a[i][m];
for(int j = 0; j < m; j++)
sum -= ans[j] * a[i][j];
if(abs(sum) > eps) return vector<double>();
}
return ans;
}