Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 浮点错误_Java_Floating Point_Rational Numbers - Fatal编程技术网

Java 浮点错误

Java 浮点错误,java,floating-point,rational-numbers,Java,Floating Point,Rational Numbers,我的浮点运算有问题。A是双人的。例如,Java中的56实际上可能存储为.56000…1 我正在试着把小数转换成小数。我试着用连分数做这个 但是,由于计算机如何存储和舍入小数,我使用这种方法的答案是不准确的 我尝试了另一种方法: public static Rational rationalize(double a){ if(a>= 1){ //throw some exception } String copOut = Double.toS

我的浮点运算有问题。A是双人的。例如,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;    
}
公共静态理性合理化(双a){
如果(a>=1){
//抛出一些异常
}
字符串copOut=Double.toString(a);
int计数器=0;
系统输出打印项次(a);
while(a%1!=0&&counter
我使用字符串来查找小数点的长度,以确定我应该乘以10的次数。我后来截断了十进制数。这让我得到了正确的答案,但感觉不是正确的方法?
有人能提出“正确”的方法吗?

事实上你做得很好。。但是,如果输入是关于
11.56
的内容,则此操作将失败。在这里,您需要执行
copOut.length()-3

要使其动态,请使用
String#split()

现在你只需要做

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

这里的第一个问题是,输入是双精度的。
,因此在任何代码执行之前,您就已经失去了精度。思考一下BigDecimal。
while(a%1 != 0 && counter < decLength.length()){
        a *= 10;
        counter++;
    }
long d = (long)Math.pow(10,decLength.length());
 a=a*d;