1 18 19 package org.apache.commons.math.linear; 20 21 22 36 public class CholeskySolver { 37 38 private double numericalZero = 10E-12; 39 40 41 private RealMatrixImpl decompMatrix; 42 43 44 47 public CholeskySolver() { 48 } 50 51 56 public void setNumericalZero(double numericalZero) { 57 this.numericalZero = numericalZero; 58 } 60 63 public double getNumericalZero() { 64 return numericalZero; 65 } 67 68 77 public void decompose(RealMatrix m) 78 throws IllegalArgumentException { 79 80 decompMatrix = null; 81 double[][] mval = m.getData(); 82 int numRows = m.getRowDimension(); 83 int numCols = m.getColumnDimension(); 84 if (numRows != numCols) 85 throw new IllegalArgumentException ("matrix is not square"); 86 double[][] decomp = new double[numRows][numCols]; 87 double sum; 88 89 for (int col=0; col<numCols; col++) { 91 92 sum = mval[col][col]; 94 for (int k=0; k<col; k++) 95 sum = sum - decomp[col][k]*decomp[col][k]; 96 if (sum <= numericalZero) { 97 throw new IllegalArgumentException ( 98 "Matrix is not positiv definit"); 99 } 100 decomp[col][col] += Math.sqrt(sum); 101 102 for (int row=col+1; row<numRows; row++) { 104 sum = mval[row][col]; 105 for (int k=0; k<col; k++) 106 sum = sum - decomp[col][k]*decomp[row][k]; 107 decomp[row][col] = sum/decomp[col][col]; 108 } 110 } 112 decompMatrix = new RealMatrixImpl(decomp); 113 114 } 116 117 123 public RealMatrixImpl getDecomposition() { 124 return decompMatrix; 125 } 127 128 140 public double[] solve(double[] c) 141 throws IllegalStateException , IllegalArgumentException { 142 143 if (decompMatrix == null) { 144 throw new IllegalStateException ("no decomposed matrix available"); 145 } if (decompMatrix.getColumnDimension() != c.length) 147 throw new IllegalArgumentException ("matrix dimension mismatch"); 148 149 double[][] decomp = decompMatrix.getData(); 150 double[] x = new double[decomp.length]; 151 double sum; 152 153 for (int i=0; i<x.length; i++) { 155 sum = c[i]; 156 for (int k=0; k<i; k++) 157 sum = sum - decomp[i][k]*x[k]; 158 x[i] = sum / decomp[i][i]; 159 } 161 for (int i=x.length-1; i>=0; i--) { 163 sum = x[i]; 164 for (int k=i+1; k<x.length; k++) 165 sum = sum - decomp[k][i]*x[k]; 166 x[i] = sum / decomp[i][i]; 167 } 169 return x; 170 } 172 173 189 public double[] solve(RealMatrix m, double[] c) 190 throws IllegalArgumentException { 191 decompose(m); 192 return solve(c); 193 } 195 196 205 public double getDeterminant() { 206 207 if (decompMatrix == null) { 208 throw new IllegalStateException ("no decomposed matrix available"); 209 } 211 double[][] data = decompMatrix.getData(); 212 double res = 1.0d; 213 for (int i=0; i<data.length; i++) { 214 res *= data[i][i]; 215 } res = res*res; 217 218 return res; 219 } 221 } | Popular Tags |