-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSystem.cpp
More file actions
43 lines (39 loc) · 1.11 KB
/
LinearSystem.cpp
File metadata and controls
43 lines (39 loc) · 1.11 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
#include "LinearSystem.h"
#include "cassert"
LinearSystem::LinearSystem(const Matrix& inputA,const Vector& inputB) : A(inputA), b(inputB), n(inputB.size())
{
assert(A.rows() == A.cols());
assert(A.rows() == b.size());
}
Vector LinearSystem::solve()
{
Matrix U = A;
Vector rhs = b;
Vector x(n);
//forward elimination
for (int k = 1; k <= n; k++)
{
double pivot = U(k, k);
assert(pivot != 0);
for (int i = k + 1; i <= n; i ++)
{
double factor = U(i, k)/ pivot;
for (int j = k; j <= n; j++)
{
U(i, j) -= factor * U(k, j);
}
rhs(i) -= factor * rhs(k);
}
}
//back substitution
for (int i = n; i >= 1; i--)
{
double sum = rhs(i);
for (int j = i + 1; j <= n; j++)
{
sum -= U(i, j) * x(j);
}
x(i) = sum / U(i, i);
}
return x;
}