2014-02-18 82 views
0

我遇到浮點問題。雙。例如,Java中的56可能實際上存儲爲.56000 ... 1。浮點錯誤

我想將小數轉換爲分數。我想如何計算機存儲和小數四捨五入來做到這一點使用連分數

Continuous Fractions

,但使用這種方法我的答案是不準確的,由於。

我嘗試另一種方法:

public static Rational rationalize(double a){ 
     if(a>= 1){ 
     //throw some exception 
    } 
    String copOut = Double.toString(a); 

    int counter = 0; 
    System.out.println(a); 
    while(a%1 != 0 && counter < copOut.length() - 2){ 
     a *= 10; 
     counter++; 
    } 
    long deno = (long)Math.pow(10,counter);//sets the denominator 
    Rational frac = new Rational((long)a,deno)//the unsimplified rational number 
    long gcd = frac.gcd(); 
    long fnum = frac.getNumer();//gets the numerator 
    long fden = frac.getDenom();//gets the denominator 
    frac = new Rational(fnum/gcd, fden/gcd); 
    return frac;  
} 

我使用的字符串,找到小數的長度來確定我要多少時間乘以10後,我截斷小數。這給我正確的答案,但它不覺得正確的做法? 有人可以建議「正確」的方式來做到這一點?

+0

第一個問題在這裏是* input *是'double.'因此,在任何代碼執行之前,您已經失去了精度。想一想'BigDecimal.' – EJP

回答

1

其實你做得很好......但如果輸入是關於11.56的東西,那麼這將失敗。這裏你需要做copOut.length() - 3

爲了使動態使用String#split()

String decLength = copOut.split("\\.")[1]; //this will result "56" (Actual string after decimal) 

現在,你需要做的僅僅只是

while(a%1 != 0 && counter < decLength.length()){ 
     a *= 10; 
     counter++; 
    } 

如果你想刪除的循環再使用

long d = (long)Math.pow(10,decLength.length()); 
a=a*d;