Continued Fractions

numerics4j provides the means to create and evaluate arbitrary continued fractions. See Continued Fraction for an in depth definition of continued fractions. To create a continued fraction, simply subclass ContinuedFraction and provide implementations for the getA and getB methods, which return the continued fraction terms.

The ContinuedFraction class is quite flexible with regards to the variety of continued fractions it can represent. For example it can be used on very basic continued fractions, ones having all constant terms like the golden ratio constant:

ContinuedFraction goldenRatio = new ContinuedFraction() {
    public double getA(int n, double x) {
        return 1.0;
    }

    public double getB(int n, double x) {
        return 1.0;
    }
};

double x = goldenRatio.evaluate(0.0);  // returns 1.6180339887499... for all input values.

Also, the ContinuedFraction class can represent continued fractions whose terms are functions of their indices. An example of this type of continued fraction can be used to compute the constant e:

ContinuedFraction e = new ContinuedFraction() {
    public double getA(int n, double x) {
        return n + 1.0;
    }

    public double getB(int n, double x) {
        return n;
    }
};

double x = 2.0 + 1.0 / e.evaluate(0.0);

The most involved type of continued fractions are ones whose terms are not only functions of their indices, but also functions of an evaluation point. A lot of transcendental functions have continued fraction representations. As such, these functions can be evaluated numerically using the ContinuedFraction class. For example, the exponetial function can be evaulated with a continued fraction:

ContinuedFraction exponential = new ContinuedFraction() {
    public double getA(int n, double x) {
        if (n == 0) {
            return 1.0;
        } else if (n % 2 == 0) { // even
            return 2.0;
        } else { // odd
            return n;
        }
    }

    public double getB(int n, double x) {
        if (n % 2 == 0) { // even
            return x;
        } else { // odd
            return -x;
        }
    }
};

double x = exponential.evaluate(2.0); // Math.exp(2.0)
double x = exponential.evaluate(4.0); // Math.exp(4.0)