Java – what’s wrong with this simple “double” calculation?

See English answers > how to resolve a Java routing double issue13

I know that some decimal numbers cannot be represented correctly in floating-point / double binary format, but with the variable D3, Java can store and display 2.64 without any problem

double d1 = 4.64;
double d2 = 2.0;
double d3 = 2.64;
double d4 = d1 - d2;

System.out.println("d1      : " + d1);
System.out.println("d2      : " + d2);
System.out.println("d3      : " + d3);
System.out.println("d4      : " + d4);
System.out.println("d1 - d2 : " + (d1 - d2));

answer,

d1      : 4.64
d2      : 2.0
d3      : 2.64
d4      : 2.6399999999999997
d1 - d2 : 2.6399999999999997

Solution

problem

Binary 2.64 is a 10.1010001111010111000010101000111101 loop, in other words, it cannot be represented in binary, so there is a small error Java is good for D3, but once the actual calculation involves it, it must fall on the real performance

Binary Calculator

more:

2.64= 10.10100011110101110000101000111101
4.64=100.1010001111010111000010100011110

Now, even in these two cases,. 64 is the same, because 4 = 100 uses more double significant digits than 2 = 10, so when you say. 64 of 4.64-2.0 and 2.64, expressed with different rounding errors in these two cases, the lost information cannot be restored to the final answer

Note: I don't use the important numbers of double numbers here, no matter what the binary calculator will produce, but the effect is the same, no matter the significant numbers of the numbers

Do not assume that double values are accurate (although their inaccuracies are microscopic, just because some numbers cannot be represented in binary)

Floating point numbers are not accurate, but they can only be seen from the decimal point

Although you should always expect double precision to have small errors in the last few decimal places, it is wrong to treat binary representation as "bad" or worse decimal

We are used to some numbers (such as 1 / 3) that cannot be expressed in decimal. We accept that such a number will eventually be 0.333 instead of the real value (I can't write down infinite space); In this case, binary numbers cannot be accurately expressed 1 / 10 is a number that cannot be accurately expressed in binary; It's just because we're used to the decimal system

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>