文字和计算中的浮点精度 [英] Floating point precision in literals vs calculations
问题描述
例如:
double num1 = 0.3;
double num2 = 0.1 + 0.2;
System.out.println(num1);
System.out.println(num2);
为什么结果是:
<$ p $而不是: 0.3
0.30000000000000004
而不是:
0.30000000000000004
0.30000000000000004
当没有0.3的确切的二进制表示。
我知道BigDecimal类,但我不太明白这个原始数字的不一致性。
三个数字可以完全表示为 double
。得到不同结果的原因是,在 0.1
加到 0.2
之后的值与<$有不同的表示误差C $ C> 0.3 。在打印结果( demo )时,大约5.5E-17的差异足以导致差异。 p>
double a = 0.2;
double b = 0.1;
double c = 0.3;
double d = a + b;
double e = d-c; //这是5.551115123125783E-17
I'm wondering why floating point numbers in Java can represent exact value when they are initialized as literals, but they are approximate when they represent result of some calculation. For example:
double num1 = 0.3;
double num2 = 0.1 + 0.2;
System.out.println(num1);
System.out.println(num2);
why the result is:
0.3
0.30000000000000004
and not:
0.30000000000000004
0.30000000000000004
When there is no exact binary representation of 0.3. I know the BigDecimal class, but I don't quite understand this primitive numbers inconsistency.
None of the three numbers can be represented exactly as a double
. The reason that you get different results is that the value after adding 0.1
to 0.2
has a different representation error than 0.3
. The difference of about 5.5E-17 is enough to cause a difference when printing out the result (demo).
double a = 0.2;
double b = 0.1;
double c = 0.3;
double d = a+b;
double e = d-c; // This is 5.551115123125783E-17
这篇关于文字和计算中的浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!