[英]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.