Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point precision in literals vs calculations

I'm wondering why floating point numbers in Java can represent exact value when they are initialized as literals, but they are approximate when they represent result of some calculation. For example:

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

why the result is:

0.3
0.30000000000000004

and not:

0.30000000000000004
0.30000000000000004

When there is no exact binary representation of 0.3. I know the BigDecimal class, but I don't quite understand this primitive numbers inconsistency.

like image 971
swch Avatar asked Feb 15 '15 16:02

swch


2 Answers

None of the three numbers can be represented exactly as a double. The reason that you get different results is that the value after adding 0.1 to 0.2 has a different representation error than 0.3. The difference of about 5.5E-17 is enough to cause a difference when printing out the result (demo).

double a = 0.2;
double b = 0.1;
double c = 0.3;
double d = a+b;
double e = d-c; //  This is 5.551115123125783E-17
like image 174
Sergey Kalinichenko Avatar answered Sep 28 '22 07:09

Sergey Kalinichenko


When 0.3 is converted to its representation as ones and zeroes then converted back to decimal, it rounds to 0.3. However, when 0.1 and 0.2 are respectively converted to binary, the errors add up upon addition so as to show up when the sum is converted back to decimal. A thorough explanation would involve demonstrating the IEEE representation of each number along with the addition and conversions. A bit involved, but I hope you got the idea.

like image 21
Tarik Avatar answered Sep 28 '22 05:09

Tarik