Double precision theorem

The following expression returns false (e.g. in Java and C #)

0.1 + 0.1 + 0.1 == 0.3

So, we learned that we always compare doubles and swim like this

Math.abs(double1 - double2) < epsilon

But why

0.1 + 0.1 == 0.2 returns true and 
0.1 + 0.1 + 0.1 == 0.3 returns false?

I know this has something to do with the mantissa, but I don't get it for sure.

+4
source share
2 answers

Float / double are stored as binary fractions, not decimal fractions.

There are some numbers that cannot be fully represented by our decimal notation. For example, 1/3 in decimal notation is 0.33333333 ... The same thing happens in binary notation, except that the numbers that cannot be represented exactly are different. Among them, the number 1/10. In a binary record that is 0.000110011001100 ...

, . .

, : 0.1 + 0.1 + 0.1 == 0.3, , , , .

+6

@msporek . , .

0.1 + 0.1 , IEEE 754:

    Dec    IEEE 754           52-bit mantisse
             ----------------------------------------------------
    0.1 =  1.1001100110011001100110011001100110011001100110011010 * 2^-4
    0.1 =  1.1001100110011001100110011001100110011001100110011010 * 2^-4
 +  -------------------------------------------------------------------
    0.2 = 11.0011001100110011001100110011001100110011001100110100 * 2^-4
        =  1.1001100110011001100110011001100110011001100110011010 * 2^-3

, , 0.2 IEEE 754 0,1 0,1 IEEE 754 . : 0.2 + 0.1

    Dec    IEEE 754            52-bit mantisse
             ----------------------------------------------------
    0.2 =  1.1001100110011001100110011001100110011001100110011010 * 2^-3
    0.1 =  1.1001100110011001100110011001100110011001100110011010 * 2^-4
 +  -------------------------------------------------------------------
    0.2 =  1.1001100110011001100110011001100110011001100110011010 * 2^-3
    0.1 =  0.1100110011001100110011001100110011001100110011001101 * 2^-3
 +  -------------------------------------------------------------------
    0.3 = 10.0110011001100110011001100110011001100110011001100111  * 2^-3
        =  1.00110011001100110011001100110011001100110011001100111 * 2^-2
        =  1.0011001100110011001100110011001100110011001100110100  * 2^-2
                                                              ^^^
                                                          These bits

: 100. 0.3 011 . ( ).

, FPU 80 mantisse, , , -, . , 52 .

IEEE 754 :
, , :

        Dec    IEEE 754            52-bit mantisse
                 ----------------------------------------------------
        0.3 =  1.0011001100110011001100110011001100110011001100110011 * 2^-2
  0.2 + 0.1 =  1.0011001100110011001100110011001100110011001100110100 * 2^-2

: .

+4

Source: https://habr.com/ru/post/1569285/


All Articles