gpt4 book ai didi

java - Java 中的浮点精度和相等性

转载 作者:行者123 更新时间:2023-12-02 04:10:32 25 4
gpt4 key购买 nike

众所周知, float ,即使是十进制格式的小数点后位数固定的 float ,也无法准确表示。所以我有以下程序来测试:

public class Main {
public static void main(String[] args) {
System.out.printf("0.1 in single precision is %.50f\n", 0.1f);
System.out.printf("0.2 in single precision is %.50f\n", 0.2f);
System.out.printf("0.3 in single precision is %.50f\n", 0.3f);
System.out.printf("0.1 + 0.2 in single precision is %.50f\n", 0.1f + 0.2f);
System.out.printf("0.1 + 0.2 == 0.3 is %b in single precision\n", 0.1123f * 0.4f + 0.2f * 0.5f == 0.2f * 0.7f + 0.0123f * 0.4f);

System.out.println();

System.out.printf("0.1 in double precision is %.50f\n", 0.1);
System.out.printf("0.2 in double precision is %.50f\n", 0.2);
System.out.printf("0.3 in double precision is %.50f\n", 0.3);
System.out.printf("0.1 + 0.2 in double precision is %.50f\n", 0.1 + 0.2);
System.out.printf("0.1 + 0.2 == 0.3 is %b in double precision\n", 0.1 + 0.2 == 0.3);
}
}

输出如下:

0.1 in single precision is 0.10000000149011612000000000000000000000000000000000
0.2 in single precision is 0.20000000298023224000000000000000000000000000000000
0.3 in single precision is 0.30000001192092896000000000000000000000000000000000
0.1 + 0.2 in single precision is 0.30000001192092896000000000000000000000000000000000
0.1 + 0.2 == 0.3 is true in single precision

0.1 in double precision is 0.10000000000000000000000000000000000000000000000000
0.2 in double precision is 0.20000000000000000000000000000000000000000000000000
0.3 in double precision is 0.30000000000000000000000000000000000000000000000000
0.1 + 0.2 in double precision is 0.30000000000000004000000000000000000000000000000000
0.1 + 0.2 == 0.3 is false in double precision

从上述结果中我无法回答两个问题,我正在寻求帮助:

  1. 为什么 0.10.20.3 的双重表示看起来很精确,而 0.1 + 0.2 却不然't。
  2. 为什么 0.1f + 0.2f == 0.3f 返回 true?

最佳答案

  1. 我怀疑 System.out.printf 在这里是否正常工作。获得与 0.1 相同的精确 double 值的可靠方法是编写 new BigDecimal(0.1).toString()
  2. “为什么 0.1f + 0.2f == 0.3f 返回 true?”很大程度上是因为您很幸运:将 0.1 舍入到最接近的浮点表示形式,将 0.2 舍入到最接近的浮点表示形式,然后将它们相加,得到最接近的可表示浮点形式为 0.3。一般来说,情况并非如此,这些值(value)观只是碰巧起作用。

关于java - Java 中的浮点精度和相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33832574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com