1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.hipparchus.linear;
24
25 import org.hipparchus.exception.MathIllegalArgumentException;
26 import org.junit.jupiter.api.Test;
27
28 import static org.junit.jupiter.api.Assertions.assertEquals;
29 import static org.junit.jupiter.api.Assertions.fail;
30
31
32 class CholeskySolverTest {
33
34 private double[][] testData = new double[][] {
35 { 1, 2, 4, 7, 11 },
36 { 2, 13, 23, 38, 58 },
37 { 4, 23, 77, 122, 182 },
38 { 7, 38, 122, 294, 430 },
39 { 11, 58, 182, 430, 855 }
40 };
41
42
43 @Test
44 void testSolveDimensionErrors() {
45 DecompositionSolver solver =
46 new CholeskyDecomposition(MatrixUtils.createRealMatrix(testData)).getSolver();
47 RealMatrix b = MatrixUtils.createRealMatrix(new double[2][2]);
48 try {
49 solver.solve(b);
50 fail("an exception should have been thrown");
51 } catch (MathIllegalArgumentException iae) {
52
53 }
54 try {
55 solver.solve(b.getColumnVector(0));
56 fail("an exception should have been thrown");
57 } catch (MathIllegalArgumentException iae) {
58
59 }
60 try {
61 solver.solve(new ArrayRealVectorTest.RealVectorTestImpl(b.getColumn(0)));
62 fail("an exception should have been thrown");
63 } catch (MathIllegalArgumentException iae) {
64
65 }
66 }
67
68
69 @Test
70 void testSolve() {
71 DecompositionSolver solver =
72 new CholeskyDecomposition(MatrixUtils.createRealMatrix(testData)).getSolver();
73 RealMatrix b = MatrixUtils.createRealMatrix(new double[][] {
74 { 78, -13, 1 },
75 { 414, -62, -1 },
76 { 1312, -202, -37 },
77 { 2989, -542, 145 },
78 { 5510, -1465, 201 }
79 });
80 RealMatrix xRef = MatrixUtils.createRealMatrix(new double[][] {
81 { 1, 0, 1 },
82 { 0, 1, 1 },
83 { 2, 1, -4 },
84 { 2, 2, 2 },
85 { 5, -3, 0 }
86 });
87
88
89 assertEquals(0, solver.solve(b).subtract(xRef).getNorm1(), 1.0e-13);
90
91
92 for (int i = 0; i < b.getColumnDimension(); ++i) {
93 assertEquals(0,
94 solver.solve(b.getColumnVector(i)).subtract(xRef.getColumnVector(i)).getNorm(),
95 1.0e-13);
96 }
97
98
99 for (int i = 0; i < b.getColumnDimension(); ++i) {
100 ArrayRealVectorTest.RealVectorTestImpl v =
101 new ArrayRealVectorTest.RealVectorTestImpl(b.getColumn(i));
102 assertEquals(0,
103 solver.solve(v).subtract(xRef.getColumnVector(i)).getNorm(),
104 1.0e-13);
105 }
106
107 }
108
109
110 @Test
111 void testDeterminant() {
112 assertEquals(7290000.0, getDeterminant(MatrixUtils.createRealMatrix(testData)), 1.0e-15);
113 }
114
115 private double getDeterminant(RealMatrix m) {
116 return new CholeskyDecomposition(m).getDeterminant();
117 }
118
119 }