-
Notifications
You must be signed in to change notification settings - Fork 0
/
LUdecomposition.c
63 lines (52 loc) · 1.36 KB
/
LUdecomposition.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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void ludecomp(size_t n, const float *A, float *L, float *U)
{
if (n == 0)
{
return;
}
// allocate buffer size for L and U , A will be given so we don't need to allocate
size_t buffersize = n * n * sizeof(float);
float *Lbuffer = (float *)malloc(buffersize);
float *Ubuffer = (float *)malloc(buffersize);
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < n; j++)
{
if (i == j)
{
L[i * n + j] = 1.0f;
U[i * n + j] = A[i * n + j];
}
else
{
L[i * n + j] = 0.0f;
U[i * n + j] = A[i * n + j];
}
}
}
// calculation of L and U
for (size_t i = 0; i < n - 1; i++)
{
float temp = U[i * n + i];
if (temp == 0)
{
temp = 1; // Prevent division by zero
}
for (size_t j = i + 1; j < n; j++)
{
// Calculating constant and placing it in L
L[j * n + i] = U[j * n + i] / temp;
// Calculation of the new values
for (size_t k = i; k < n; k++)
{
U[j * n + k] -= L[j * n + i] * U[i * n + k];
}
}
}
// O(n^3): 3 inner loops
free(Lbuffer);
free(Ubuffer);
}