Continuous Fractions

醉酒当歌 提交于 2020-01-15 06:53:11

问题


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);
    }       
}

回答1:


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




回答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.



来源:https://stackoverflow.com/questions/21843649/continuous-fractions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!