Question

I have messed with code execution result.

code:

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

output:

true
false

I know that 0.2 and 0.3 cannot transform to binary correct.

Why do I see different results?

UPDATE:

Can I predict result in similar issues without compiler?

Was it helpful?

Solution 3

PHP gave this:

<?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

The reaseon for the first to 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);
?>

Output

0.20000000000000001110
0.30000000000000004441

0.20000000000000001110
0.29999999999999998890

OTHER TIPS

System.out.println(0.1+0.1+0.1);

output

0.30000000000000004

There is a rounding error on floating point arithmetics. Some values are can not be represented in base 2, you can't rely on comparing float numbers. 0.1 in base-2 is like 1/3 in base-10.

You can see the link below

What Every Computer Scientist Should Know About Floating-Point Arithmetic

What you see is the fact that floating point values are not very accurate and you should not for example compare them using == operator. For comparisons you should use epsilon compares, ie. for two floating point values f1 and f2

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

Where EPSILON is some very small floating point value

You cannot rely on == to work well for float numbers, whose results are undependable because they cannot be represented accurately on computers. When you want to check two float numbers equal or not, use fabs(a-b) < epsilon instead.

P.S. The following test are under C++, which gives surprising results (just for fun to show how un-dependable 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top