有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

浮动精度Java float比double更精确?

代码:

class Main {
    public static void main (String[] args) {
        System.out.print("float: ");
        System.out.println(1.35f-0.00026f);
        System.out.print("double: ");
        System.out.println(1.35-0.00026);
    }
}

输出:

float: 1.34974
double: 1.3497400000000002

???float得到了正确的答案,但是double从哪里添加了额外的东西,为什么

double不应该比float更精确吗


共 (3) 个答案

  1. # 1 楼答案

    If you know something about the rules for converting double values to strings, which are specified by the documentation for Double.toString [Java-API], you know that the program prints the shortest decimal fraction sufficient to distinguish the double value from its nearest neighbor, with at least one digit before and after the decimal point.

    查看Joshua Bloch的《Java谜题:陷阱、陷阱和角落案例》——谜题2:是时候改变了。他在那一章中解释了这个问题

  2. # 2 楼答案

    其原因是浮点数运算的数字机制。 此外,当java试图打印浮点值时,它会截断尾随的零。 你知道,double类型使用8字节,float使用4字节。因此,双精度更高

    所以,当java计算浮点值时,它会得到1.3497400,并在输出之前将其截断。 当java计算你的双精度值时,它会得到更多的数字,所以你会得到这样的结果

    为了更好地理解,请尝试执行以下简单示例:

    public class Test {
        public static void main( String[] args ) {
            float sum = 0;
            for (int i = 1; i <= 10; i++) {
                sum += 0.1;
            }
            System.out.println( sum );
        }
    }
    
    public class Test {
        public static void main( String[] args ) {
            double sum = 0;
            for (int i = 1; i <= 10; i++) {
                sum += 0.1;
            }
            System.out.println( sum );
        }
    }
    
  3. # 3 楼答案

    float是4字节宽,而double是8字节宽

    勾选What Every Computer Scientist Should Know About Floating-Point Arithmetic

    当然,双精度精度更高,所以舍入误差略小

    Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

    旁注:-

    我建议如果你想要精确的十进制值,那么使用java.math.BigDecimal