1 16 package org.apache.commons.math.util; 17 18 import java.io.Serializable ; 19 20 import org.apache.commons.math.ConvergenceException; 21 import org.apache.commons.math.MathException; 22 23 37 public abstract class ContinuedFraction implements Serializable { 38 39 40 static final long serialVersionUID = 1768555336266158242L; 41 42 43 private static final double DEFAULT_EPSILON = 10e-9; 44 45 48 protected ContinuedFraction() { 49 super(); 50 } 51 52 59 protected abstract double getA(int n, double x); 60 61 68 protected abstract double getB(int n, double x); 69 70 76 public double evaluate(double x) throws MathException { 77 return evaluate(x, DEFAULT_EPSILON, Integer.MAX_VALUE); 78 } 79 80 87 public double evaluate(double x, double epsilon) throws MathException { 88 return evaluate(x, epsilon, Integer.MAX_VALUE); 89 } 90 91 98 public double evaluate(double x, int maxIterations) throws MathException { 99 return evaluate(x, DEFAULT_EPSILON, maxIterations); 100 } 101 102 119 public double evaluate(double x, double epsilon, int maxIterations) 120 throws MathException 121 { 122 double[][] f = new double[2][2]; 123 double[][] a = new double[2][2]; 124 double[][] an = new double[2][2]; 125 126 a[0][0] = getA(0, x); 127 a[0][1] = 1.0; 128 a[1][0] = 1.0; 129 a[1][1] = 0.0; 130 131 return evaluate(1, x, a, an, f, epsilon, maxIterations); 132 } 133 134 148 private double evaluate( 149 int n, 150 double x, 151 double[][] a, 152 double[][] an, 153 double[][] f, 154 double epsilon, 155 int maxIterations) throws MathException 156 { 157 double ret; 158 159 an[0][0] = getA(n, x); 161 an[0][1] = 1.0; 162 an[1][0] = getB(n, x); 163 an[1][1] = 0.0; 164 165 f[0][0] = (a[0][0] * an[0][0]) + (a[0][1] * an[1][0]); 167 f[0][1] = (a[0][0] * an[0][1]) + (a[0][1] * an[1][1]); 168 f[1][0] = (a[1][0] * an[0][0]) + (a[1][1] * an[1][0]); 169 f[1][1] = (a[1][0] * an[0][1]) + (a[1][1] * an[1][1]); 170 171 if (Math.abs((f[0][0] * f[1][1]) - (f[1][0] * f[0][1])) < 173 Math.abs(epsilon * f[1][0] * f[1][1])) 174 { 175 ret = f[0][0] / f[1][0]; 176 } else { 177 if (n >= maxIterations) { 178 throw new ConvergenceException( 179 "Continued fraction convergents failed to converge."); 180 } 181 ret = evaluate(n + 1, x, f 183 , an 184 , a 185 , epsilon, maxIterations); 186 } 187 188 return ret; 189 } 190 } 191 | Popular Tags |