Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

surprising double comparison [duplicate]

Tags:

java

primitive

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?

like image 274
gstackoverflow Avatar asked Dec 20 '22 18:12

gstackoverflow


2 Answers

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

like image 115
Orhan Obut Avatar answered Jan 04 '23 15:01

Orhan Obut


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

like image 36
marcinj Avatar answered Jan 04 '23 14:01

marcinj