[英]Floating point errors
我在使用浮點數時遇到麻煩。 一個雙。 例如,Java中的56實際上可能存儲為.56000 ... 1。
我正在嘗試將小數轉換為分數。 我嘗試使用連續分數來做到這一點
但由於如何計算機存儲和四舍五入小數,我使用該方法的答案不准確。
我嘗試了另一種方法:
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的時間。我稍后將截斷小數。 這給了我正確的答案,但是感覺不像是正確的方法嗎? 有人可以建議這樣做的“正確”方法嗎?
實際上,您的工作很棒。但是,如果Input約為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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.