Continued Fractions

numerics4c++ 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 create a new continued_fraction instance providing functors for the a and b coefficients, which return the continued fraction terms.

The continued_fraction 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:

double golden_ratio(unsigned int n, double x) {
    return 1.0;
}

num::continued_fraction<num::continued_fraction_coefficient, num::continued_fraction_coefficient>
    goldenRatio(golden_ratio, golden_ratio);
    
double x = goldenRatio.evaluate(0.0);  // returns 1.6180339887499... for all input values.

Also, the continued_fraction 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:

double e_a(unsigned int n, double x) {
    return n + 1.0;
}

double e_b(unsigned int n, double x) {
    return n;
}

num::continued_fraction<num::continued_fraction_coefficient, num::continued_fraction_coefficient>
    e(e_a, e_b);
    
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 continued_fraction class. For example, the exponetial function can be evaluated with a continued fraction:

double exponential_a(unsigned int n, double x) {
    if (n == 0) {
        return 1.0;
    } else if (n % 2 == 0) { // even
        return 2.0;
    } else { // odd
        return n;
    }
}

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

num::continued_fraction<num::continued_fraction_coefficient, num::continued_fraction_coefficient>
    exponential(exponential_a, exponential_b);
    
double x = exponential.evaluate(2.0); // std::exp(2.0)
       x = exponential.evaluate(4.0); // std::exp(4.0)