3

My understanding of continuous fractions was that it will always give a representation of a decimal in fraction form. I thought that continuous fraction would always return value less than or equal to the decimal number. Unfortunately my code occasionally returns fractional values greater than the decimal input.

Is my understanding of continuous fractions correct? If so can you please explain where in my code the error lies.

public static Rational contFrac(double a, int i,int n){
    if(i<n){
        boolean neg = false;
        if(a<0){
            neg = true;//need a helper method to take care of this
        }
        double reci = Math.abs(1/a);//the reciprocal of a given decimal value
        double remain = reci%1;//the decimal portion of the reciprocal
        double intprt = reci - remain;//the 'integer' portion of the reciprocal
        Rational inter = new Rational((long)intprt);//creates a new rational number using the 'integer' portion of the reciprocal
        if(remain !=0){
            inter = inter.add(contFrac(remain,i+1,n));      
        }           
        return (reciprocal(inter));//gets the reciprocal of a rational number
    }
    else{
        return new Rational(0);
    }       
}
Zhv Z
  • 53
  • 5

2 Answers2

2

I'm sure that the computer is rounding your 1/a.

user2320861
  • 1,391
  • 2
  • 11
  • 28
  • Thanks - would that explain why I get answers that are too large when I run it for 1000s of iterations? - When I run it for a say 5 iteration I get a much closer answer. – Zhv Z Feb 18 '14 at 03:46
  • The accuracy of the n-th contiued fraction convergent is bounded by 1/F_n^2, where F_n is the n-th Fibonacci number. After 1000s of iterations, you have long exceeded the machine precision of the original number, garbage production is to be expected. – Lutz Lehmann Feb 18 '14 at 09:37
2

The convergents of continuous fractions alternate between being larger and smaller than the limit. So your observed behaviour is to be expected.

Or put another way, the limit is always in between two successive convergents.

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51