forked from MinMa1122/GaussianElimination
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgauss_solve.c
executable file
·112 lines (104 loc) · 2.95 KB
/
gauss_solve.c
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
101
102
103
104
105
106
107
108
109
110
111
112
/*----------------------------------------------------------------
* File: gauss_solve.c
*----------------------------------------------------------------
*
* Author: Marek Rychlik ([email protected])
* Date: Sun Sep 22 15:40:29 2024
* Copying: (C) Marek Rychlik, 2020. All rights reserved.
*
*----------------------------------------------------------------*/
#include <math.h>
#include "helpers.h"
void gauss_solve_in_place(const int n, double A[n][n], double b[n])
{
for(int k = 0; k < n; ++k) {
for(int i = k+1; i < n; ++i) {
/* Store the multiplier into A[i][k] as it would become 0 and be
useless */
A[i][k] /= A[k][k];
for(int j = k+1; j < n; ++j) {
A[i][j] -= A[i][k] * A[k][j];
}
b[i] -= A[i][k] * b[k];
}
} /* End of Gaussian elimination, start back-substitution. */
for(int i = n-1; i >= 0; --i) {
for(int j = i+1; j<n; ++j) {
b[i] -= A[i][j] * b[j];
}
b[i] /= A[i][i];
} /* End of back-substitution. */
}
void lu_in_place(const int n, double A[n][n])
{
for(int k = 0; k < n; ++k) {
for(int i = k; i < n; ++i) {
for(int j=0; j<k; ++j) {
/* U[k][i] -= L[k][j] * U[j][i] */
A[k][i] -= A[k][j] * A[j][i];
}
}
for(int i = k+1; i<n; ++i) {
for(int j=0; j<k; ++j) {
/* L[i][k] -= A[i][k] * U[j][k] */
A[i][k] -= A[i][j]*A[j][k];
}
/* L[k][k] /= U[k][k] */
A[i][k] /= A[k][k];
}
}
}
void lu_in_place_reconstruct(int n, double A[n][n])
{
for(int k = n-1; k >= 0; --k) {
for(int i = k+1; i<n; ++i) {
A[i][k] *= A[k][k];
for(int j=0; j<k; ++j) {
A[i][k] += A[i][j]*A[j][k];
}
}
for(int i = k; i < n; ++i) {
for(int j=0; j<k; ++j) {
A[k][i] += A[k][j] * A[j][i];
}
}
}
}
void plu(int n, double A[n][n], int P[n]) {
// Initialize permutation array P to identity
for (int i = 0; i < n; i++) {
P[i] = i;
}
// Main loop over each column
for (int k = 0; k < n - 1; k++) {
// Find the pivot element
double max = fabs(A[k][k]);
int r = k;
for (int i = k + 1; i < n; i++) {
if (fabs(A[i][k]) > max) {
max = fabs(A[i][k]);
r = i;
}
}
// Swap rows in A and update permutation vector P
if (r != k) {
// Swap rows k and r in A
for (int j = 0; j < n; j++) {
double temp = A[k][j];
A[k][j] = A[r][j];
A[r][j] = temp;
}
// Swap entries in permutation vector P
int tempP = P[k];
P[k] = P[r];
P[r] = tempP;
}
// Compute the multipliers and update the matrix
for (int i = k + 1; i < n; i++) {
A[i][k] = A[i][k] / A[k][k]; // Multiplier for L
for (int j = k + 1; j < n; j++) {
A[i][j] -= A[i][k] * A[k][j]; // Update U
}
}
}
}