static void LuDecomposition Mtr ref Mtr ref Mtr if getRows getColumns

 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
static void LuDecomposition(Mtr A, ref Mtr L, ref Mtr U)
{
if (A.getRows() != A.getColumns())
return;
int n = A.getRows();
L.makeIdentity();
for (int i = 0; i < n; ++i)
{
for (int j = i; j < n; ++j)
{
decimal temp = A.getValue(i, j);
for (int k = 0; k < i; ++k)
{
temp = temp - U.getValue(k, j) * L.getValue(i, k);
}
U.setValue(temp, i, j);
}
for (int j = i + 1; j < n; ++j)
{
decimal temp = A.getValue(j, i);
for (int k = 0; k < i; ++k)
{
temp = temp - U.getValue(k, i) * L.getValue(j, k);
}
temp = temp / U.getValue(i, i);
L.setValue(temp, j, i);
}
}
}
static void inversedLuSolver(Mtr A, Mtr b)
{
int n = A.getColumns();
Mtr L = new Mtr(n, n);
Mtr U = new Mtr(n, n);
LuDecomposition(A,ref L, ref U);
Mtr inversed = new Mtr(n, n);
for (int j = n - 1; j >= 0; --j)
{
decimal tmp = 1;
for (int k = j + 1; k < n; ++k)
tmp -= U.getValue(j, k) * inversed.getValue(k, j);
tmp /= U.getValue(j, j);
inversed.setValue(tmp, j, j);
for (int i = j - 1; i >= 0; --i)
{
tmp = 0;
for (int k = i + 1; k < n; ++k)
tmp += U.getValue(i, k) * inversed.getValue(k, j);
tmp = -tmp / U.getValue(i, i);
inversed.setValue(tmp, i, j);
}
for (int i = j - 1; i >= 0; --i)
{
tmp = 0;
for (int k = i + 1; k < n; ++k)
tmp += inversed.getValue(j, k) * L.getValue(k, i);
inversed.setValue(-tmp, j, i);
}
}
Mtr answer = inversed * b;
Console.WriteLine("LU разложение:");
Console.WriteLine("Обратная матрица:");
inversed.printMatrix();
Console.WriteLine("Ответ:");
answer.printMatrix();
Console.WriteLine("-------------------------------------");
}