-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinearalgebra.cpp
More file actions
88 lines (72 loc) · 1.96 KB
/
Copy pathlinearalgebra.cpp
File metadata and controls
88 lines (72 loc) · 1.96 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
#include <vector>
#include <string>
#include <iostream>
#include "linearalgebra.h"
#define EPS 1e-10
#define INF 10
using namespace std;
namespace la{
void printMatrix(const vector<vector<double>>& matrix) //Auxiliary print function
{
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[i].size(); j++)
{
cout << matrix[i][j] << ' ';
}
cout << "\n";
}
}
int gauss (vector < vector<double> > a, vector<double> & ans) { //Gauss elimination... kinda slow
int n = (int) a.size();
int m = (int) 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)
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) {
double c = a[i][col] / a[row][col];
for (int j=col; j<=m; ++j)
a[i][j] -= a[row][j] * c;
}
++row;
}
ans.assign (m, 0);
for (int i=0; i<m; ++i)
if (where[i] != -1)
ans[i] = a[where[i]][m] / a[where[i]][i];
for (int i=0; i<n; ++i) {
double sum = 0;
for (int j=0; j<m; ++j)
sum += ans[j] * a[i][j];
if (abs (sum - a[i][m]) > EPS)
return 0;
}
for (int i=0; i<m; ++i)
if (where[i] == -1)
return INF;
return 1;
}
vector<vector<double>> transpose(const vector<vector<double>>& matrix)
{
int rows = matrix.size();
int cols = matrix[0].size();
vector<vector<double>> tMat(cols, vector<double>(rows));
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
tMat[j][i] = matrix[i][j];
}
}
return tMat;
}
}