Thread: [Mathlib-commitlog] mathlib/Source/MathLib/Functions/specfun/_private ConvergenceException.java, N
Status: Beta
Brought to you by:
st_mueller
|
From: Stefan M. <st_...@us...> - 2007-01-05 08:55:56
|
Update of /cvsroot/mathlib/mathlib/Source/MathLib/Functions/specfun/_private In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv7351/Source/MathLib/Functions/specfun/_private Added Files: ConvergenceException.java ContinuedFraction.java Gamma.java Log Message: --- NEW FILE: ContinuedFraction.java --- /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package org.apache.commons.math.util; package MathLib.Functions.specfun._private; import java.io.Serializable; //import org.apache.commons.math.ConvergenceException; //import org.apache.commons.math.MathException; /** * Provides a generic means to evaluate continued fractions. Subclasses simply * provided the a and b coefficients to evaluate the continued fraction. * * <p> * References: * <ul> * <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html"> * Continued Fraction</a></li> * </ul> * </p> * * @version $Revision: 1.1 $ $Date: 2007/01/05 08:55:48 $ */ public abstract class ContinuedFraction implements Serializable { /** Serialization UID */ private static final long serialVersionUID = 1768555336266158242L; /** Maximum allowed numerical error. */ private static final double DEFAULT_EPSILON = 10e-9; /** * Default constructor. */ protected ContinuedFraction() { super(); } /** * Access the n-th a coefficient of the continued fraction. Since a can be * a function of the evaluation point, x, that is passed in as well. * @param n the coefficient index to retrieve. * @param x the evaluation point. * @return the n-th a coefficient. */ protected abstract double getA(int n, double x); /** * Access the n-th b coefficient of the continued fraction. Since b can be * a function of the evaluation point, x, that is passed in as well. * @param n the coefficient index to retrieve. * @param x the evaluation point. * @return the n-th b coefficient. */ protected abstract double getB(int n, double x); /** * Evaluates the continued fraction at the value x. * @param x the evaluation point. * @return the value of the continued fraction evaluated at x. * @throws MathException if the algorithm fails to converge. */ public double evaluate(double x) throws Exception { return evaluate(x, DEFAULT_EPSILON, Integer.MAX_VALUE); } /** * Evaluates the continued fraction at the value x. * @param x the evaluation point. * @param epsilon maximum error allowed. * @return the value of the continued fraction evaluated at x. * @throws MathException if the algorithm fails to converge. */ public double evaluate(double x, double epsilon) throws Exception { return evaluate(x, epsilon, Integer.MAX_VALUE); } /** * Evaluates the continued fraction at the value x. * @param x the evaluation point. * @param maxIterations maximum number of convergents * @return the value of the continued fraction evaluated at x. * @throws MathException if the algorithm fails to converge. */ public double evaluate(double x, int maxIterations) throws Exception { return evaluate(x, DEFAULT_EPSILON, maxIterations); } /** * <p> * Evaluates the continued fraction at the value x. * </p> * * <p> * The implementation of this method is based on equations 14-17 of: * <ul> * <li> * Eric W. Weisstein. "Continued Fraction." From MathWorld--A Wolfram Web * Resource. <a target="_blank" * href="http://mathworld.wolfram.com/ContinuedFraction.html"> * http://mathworld.wolfram.com/ContinuedFraction.html</a> * </li> * </ul> * The recurrence relationship defined in those equations can result in * very large intermediate results which can result in numerical overflow. * As a means to combat these overflow conditions, the intermediate results * are scaled whenever they threaten to become numerically unstable. * * @param x the evaluation point. * @param epsilon maximum error allowed. * @param maxIterations maximum number of convergents * @return the value of the continued fraction evaluated at x. * @throws MathException if the algorithm fails to converge. */ public double evaluate(double x, double epsilon, int maxIterations) throws Exception { double p0 = 1.0; double p1 = getA(0, x); double q0 = 0.0; double q1 = 1.0; double c = p1 / q1; int n = 0; double relativeError = Double.MAX_VALUE; while (n < maxIterations && relativeError > epsilon) { ++n; double a = getA(n, x); double b = getB(n, x); double p2 = a * p1 + b * p0; double q2 = a * q1 + b * q0; if (Double.isInfinite(p2) || Double.isInfinite(q2)) { // need to scale if (a != 0.0) { p2 = p1 + (b / a * p0); q2 = q1 + (b / a * q0); } else if (b != 0) { p2 = (a / b * p1) + p0; q2 = (a / b * q1) + q0; } else { // can not scale an convergent is unbounded. throw new ConvergenceException( "Continued fraction convergents diverged to +/- " + "infinity."); } } double r = p2 / q2; relativeError = Math.abs(r / c - 1.0); // prepare for next iteration c = p2 / q2; p0 = p1; p1 = p2; q0 = q1; q1 = q2; } if (n >= maxIterations) { throw new ConvergenceException( "Continued fraction convergents failed to converge."); } return c; } } --- NEW FILE: Gamma.java --- /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package org.apache.commons.math.special; package MathLib.Functions.specfun._private; //import java.io.Serializable; //import org.apache.commons.math.ConvergenceException; //import org.apache.commons.math.MathException; //import org.apache.commons.math.util.ContinuedFraction; /** * This is a utility class that provides computation methods related to the * Gamma family of functions. * * @version $Revision: 1.1 $ $Date: 2007/01/05 08:55:48 $ */ public class Gamma /*implements Serializable*/ { /** Maximum allowed numerical error. */ private static final double DEFAULT_EPSILON = 10e-9; /** Lanczos coefficients */ private static double[] lanczos = { 0.99999999999999709182, 57.156235665862923517, -59.597960355475491248, 14.136097974741747174, -0.49191381609762019978, .33994649984811888699e-4, .46523628927048575665e-4, -.98374475304879564677e-4, .15808870322491248884e-3, -.21026444172410488319e-3, .21743961811521264320e-3, -.16431810653676389022e-3, .84418223983852743293e-4, -.26190838401581408670e-4, .36899182659531622704e-5, }; /** Avoid repeated computation of log of 2 PI in logGamma */ private static final double HALF_LOG_2_PI = 0.5 * Math.log(2.0 * Math.PI); /** * Default constructor. Prohibit instantiation. */ private Gamma() { //super(); } /** * Returns the natural logarithm of the gamma function Γ(x). * * The implementation of this method is based on: * <ul> * <li><a href="http://mathworld.wolfram.com/GammaFunction.html"> * Gamma Function</a>, equation (28).</li> * <li><a href="http://mathworld.wolfram.com/LanczosApproximation.html"> * Lanczos Approximation</a>, equations (1) through (5).</li> * <li><a href="http://my.fit.edu/~gabdo/gamma.txt">Paul Godfrey, A note on * the computation of the convergent Lanczos complex Gamma approximation * </a></li> * </ul> * * @param x the value. * @return log(Γ(x)) */ public static double logGamma(double x) { double ret; if (Double.isNaN(x) || (x <= 0.0)) { ret = Double.NaN; } else { double g = 607.0 / 128.0; double sum = 0.0; for (int i = lanczos.length - 1; i > 0; --i) { sum = sum + (lanczos[i] / (x + i)); } sum = sum + lanczos[0]; double tmp = x + g + .5; ret = ((x + .5) * Math.log(tmp)) - tmp + HALF_LOG_2_PI + Math.log(sum / x); } return ret; } /** * Returns the regularized gamma function P(a, x). * * @param a the a parameter. * @param x the value. * @return the regularized gamma function P(a, x) * @throws MathException if the algorithm fails to converge. */ public static double regularizedGammaP(double a, double x) throws Exception { return regularizedGammaP(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE); } /** * Returns the regularized gamma function P(a, x). * * The implementation of this method is based on: * <ul> * <li> * <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html"> * Regularized Gamma Function</a>, equation (1).</li> * <li> * <a href="http://mathworld.wolfram.com/IncompleteGammaFunction.html"> * Incomplete Gamma Function</a>, equation (4).</li> * <li> * <a href="http://mathworld.wolfram.com/ConfluentHypergeometricFunctionoftheFirstKind.html"> * Confluent Hypergeometric Function of the First Kind</a>, equation (1). * </li> * </ul> * * @param a the a parameter. * @param x the value. * @param epsilon When the absolute value of the nth item in the * series is less than epsilon the approximation ceases * to calculate further elements in the series. * @param maxIterations Maximum number of "iterations" to complete. * @return the regularized gamma function P(a, x) * @throws MathException if the algorithm fails to converge. */ public static double regularizedGammaP(double a, double x, double epsilon, int maxIterations) throws Exception { double ret; if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) { ret = Double.NaN; } else if (x == 0.0) { ret = 0.0; } else if (a >= 1.0 && x > a) { // use regularizedGammaQ because it should converge faster in this // case. ret = 1.0 - regularizedGammaQ(a, x, epsilon, maxIterations); } else { // calculate series double n = 0.0; // current element index double an = 1.0 / a; // n-th element in the series double sum = an; // partial sum while (Math.abs(an) > epsilon && n < maxIterations) { // compute next element in the series n = n + 1.0; an = an * (x / (a + n)); // update partial sum sum = sum + an; } if (n >= maxIterations) { throw new ConvergenceException( "maximum number of iterations reached"); } else { ret = Math.exp(-x + (a * Math.log(x)) - logGamma(a)) * sum; } } return ret; } /** * Returns the regularized gamma function Q(a, x) = 1 - P(a, x). * * @param a the a parameter. * @param x the value. * @return the regularized gamma function Q(a, x) * @throws MathException if the algorithm fails to converge. */ public static double regularizedGammaQ(double a, double x) throws Exception { return regularizedGammaQ(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE); } /** * Returns the regularized gamma function Q(a, x) = 1 - P(a, x). * * The implementation of this method is based on: * <ul> * <li> * <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html"> * Regularized Gamma Function</a>, equation (1).</li> * <li> * <a href=" http://functions.wolfram.com/GammaBetaErf/GammaRegularized/10/0003/"> * Regularized incomplete gamma function: Continued fraction representations (formula 06.08.10.0003)</a></li> * </ul> * * @param a the a parameter. * @param x the value. * @param epsilon When the absolute value of the nth item in the * series is less than epsilon the approximation ceases * to calculate further elements in the series. * @param maxIterations Maximum number of "iterations" to complete. * @return the regularized gamma function P(a, x) * @throws MathException if the algorithm fails to converge. */ public static double regularizedGammaQ(final double a, double x, double epsilon, int maxIterations) throws Exception { double ret; if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) { ret = Double.NaN; } else if (x == 0.0) { ret = 1.0; } else if (x < a || a < 1.0) { // use regularizedGammaP because it should converge faster in this // case. ret = 1.0 - regularizedGammaP(a, x, epsilon, maxIterations); } else { // create continued fraction ContinuedFraction cf = new ContinuedFraction() { protected double getA(int n, double x) { return ((2.0 * n) + 1.0) - a + x; } protected double getB(int n, double x) { return n * (a - n); } }; ret = 1.0 / cf.evaluate(x, epsilon, maxIterations); ret = Math.exp(-x + (a * Math.log(x)) - logGamma(a)) * ret; } return ret; } } --- NEW FILE: ConvergenceException.java --- /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package org.apache.commons.math; package MathLib.Functions.specfun._private; //import java.io.Serializable; /** * Error thrown when a numerical computation can not be performed because the * numerical result failed to converge to a finite value. * * @version $Revision: 1.1 $ $Date: 2007/01/05 08:55:48 $ */ public class ConvergenceException extends Exception /*implements Serializable*/{ /** Serializable version identifier */ private static final long serialVersionUID = -3657394299929217890L; /** * Default constructor. */ public ConvergenceException() { this(null, null); } /** * Construct an exception with the given message. * @param message descriptive error message. */ public ConvergenceException(String message) { this(message, null); } /** * Construct an exception with the given message and root cause. * @param message descriptive error message. * @param cause root cause. */ public ConvergenceException(String message, Throwable cause) { super(message, cause); } /** * Create an exception with a given root cause. * @param throwable caught exception causing this problem */ public ConvergenceException(Throwable throwable) { this(null, throwable); } } |