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