Skip to content

Commit 1202d09

Browse files
committed
Added LU decomposition algorthim
1 parent d992ac5 commit 1202d09

File tree

2 files changed

+43
-15
lines changed

2 files changed

+43
-15
lines changed

src/main/java/com/thealgorithms/matrix/LUDecomposition.java

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -85,19 +85,4 @@ public static void printMatrix(double[][] m) {
8585
System.out.println("]");
8686
}
8787
}
88-
89-
/**
90-
* Demonstration (doctest)
91-
*/
92-
public static void main(String[] args) {
93-
double[][] a = {{2, -1, -2}, {-4, 6, 3}, {-4, -2, 8}};
94-
95-
LU result = decompose(a);
96-
97-
System.out.println("l matrix:");
98-
printMatrix(result.l);
99-
100-
System.out.println("\nu matrix:");
101-
printMatrix(result.u);
102-
}
10388
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.thealgorithms.matrix;
2+
3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class LUDecompositionTest {
8+
9+
@Test
10+
public void testLUDecomposition() {
11+
double[][] A = {
12+
{4, 3},
13+
{6, 3}
14+
};
15+
16+
// Perform LU decomposition
17+
LUDecomposition.LU lu = LUDecomposition.decompose(A);
18+
double[][] L = lu.l;
19+
double[][] U = lu.u;
20+
21+
// Reconstruct A from L and U
22+
double[][] reconstructed = multiplyMatrices(L, U);
23+
24+
// Assert that reconstructed matrix matches original A
25+
for (int i = 0; i < A.length; i++) {
26+
assertArrayEquals(A[i], reconstructed[i], 1e-9);
27+
}
28+
}
29+
30+
// Helper method to multiply two matrices
31+
private double[][] multiplyMatrices(double[][] A, double[][] B) {
32+
int n = A.length;
33+
double[][] C = new double[n][n];
34+
for (int i = 0; i < n; i++) {
35+
for (int j = 0; j < n; j++) {
36+
for (int k = 0; k < n; k++) {
37+
C[i][j] += A[i][k] * B[k][j];
38+
}
39+
}
40+
}
41+
return C;
42+
}
43+
}

0 commit comments

Comments
 (0)