2014-02-18 59 views
2

我對連續分數的理解是,它總會給出分數形式的小數表示。我認爲連續分數總是會返回小於或等於十進制數的值。不幸的是,我的代碼偶爾會返回大於十進制輸入的分數值。連續分數

我對連續分數的理解是否正確?如果可以,請解釋我的代碼中的錯誤在哪裏。

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

這甚至意味着如何編譯? 'reci'被引用爲局部變量,而不是方法。 – Makoto

+0

應該是「繼續分數」(http://en.wikipedia.org/wiki/Continued_fraction) – colcarroll

回答

2

我確定計算機正在四捨五入你的1/a

+0

謝謝 - 這會解釋爲什麼我在運行迭代1000次時得到的答案太大了嗎? - 當我爲5次迭代運行它時,我得到了更接近的答案。 –

+0

第n個收斂分數收斂的精度受1/F_n^2限制,其中F_n是第n個斐波那契數。經過1000多次迭代後,你已經超過原始數字的機器精度,垃圾產生是可以預料的。 – LutzL

1

連續分數的收斂在大於和小於極限之間交替。所以你的觀察行爲是可以預料的。或者換句話說,限制總是在兩個連續的會聚之間。