Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuous Fractions

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);
    }       
}
like image 339
Zhv Z Avatar asked Jul 09 '26 22:07

Zhv Z


1 Answers

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

like image 165
user2320861 Avatar answered Jul 14 '26 16:07

user2320861



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!