Amazing Double Comparison

I messed up the code execution result.

code:

System.out.println(0.2==0.1+0.1);
System.out.println(0.3==0.1+0.1+0.1);

exit:

true
false

I know that 0.2 and 0.3 cannot be converted to binary.

Why do I see different results?

UPDATE:

Is it possible to predict the result in such problems without a compiler?

+4
source share
4 answers

PHP gave the following:

<?php

printf("%0.20f\n", 0.1+0.1);
printf("%0.20f\n", 0.1+0.1+0.1);

?>
0.20000000000000001110
0.30000000000000004441

and

<?php
  echo 0.2==0.1+0.1?"true\n":"false\n";
  echo 0.3==0.1+0.1+0.1?"true\n":"false\n";
?>
true
false

Reason for the first will be "true":

<?php
   printf("%0.20f\n", 0.1+0.1);
   printf("%0.20f\n", 0.1+0.1+0.1);
   echo "\n";
   printf("%0.20f\n", 0.2);
   printf("%0.20f\n", 0.3);
?>

Exit

0.20000000000000001110
0.30000000000000004441

0.20000000000000001110
0.29999999999999998890
0
source
System.out.println(0.1+0.1+0.1);

output

0.30000000000000004

There is a rounding error in floating point arithmetic. Some values ​​cannot be represented in base 2; you cannot rely on comparing floating point numbers. 0.1 in base-2 is 1/3 in base-10.

You can see the link below.

+9

, , , , ==. epsilon, . f1 f2

if  (Math.abs(f1 - f2) < EPSILON ) {
   // they are equal
}

EPSILON -

+2

==, float, , . float, , fabs(a-b) < epsilon .

PS The next test is under C++, which gives unexpected results (just to show how independent it is):

cout << (0.1==0.1) << endl;                                // true
cout << (0.2==0.1+0.1) << endl;                            // true
cout << (0.3==0.1+0.1+0.1) << endl;                        // false
cout << (0.4==0.1+0.1+0.1+0.1) << endl;                    // true
cout << (0.5==0.1+0.1+0.1+0.1+0.1) << endl;                // true
cout << (0.6==0.1+0.1+0.1+0.1+0.1+0.1) << endl;            // true
cout << (0.7==0.1+0.1+0.1+0.1+0.1+0.1+0.1) << endl;        // true        
cout << (0.8==0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1) << endl;    // false
0
source

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


All Articles