Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Glitch? Subtracting numbers?

Is this a glitch in Java?

I go to solve this expression: 3.1 - 7.1

I get the answer: -3.9999999999999996

What is going on here?

like image 529
Dylan Wheeler Avatar asked Nov 11 '11 20:11

Dylan Wheeler


1 Answers

A great explanation can be found here. http://www.ibm.com/developerworks/java/library/j-jtp0114/

Floating point arithmetic is rarely exact. While some numbers, such as 0.5, can be exactly represented as a binary (base 2) decimal (since 0.5 equals 2-1), other numbers, such as 0.1, cannot be. As a result, floating point operations may result in rounding errors, yielding a result that is close to -- but not equal to -- the result you might expect. For example, the simple calculation below results in 2.600000000000001, rather than 2.6:

double s=0;

for (int i=0; i<26; i++)
    s += 0.1;
System.out.println(s); 

Similarly, multiplying .1*26 yields a result different from that of adding .1 to itself 26 times. Rounding errors become even more serious when casting from floating point to integer, because casting to an integral type discards the non-integral portion, even for calculations that "look like" they should have integral values. For example, the following statements:

  double d = 29.0 * 0.01;
  System.out.println(d);
  System.out.println((int) (d * 100));

will produce as output:

 0.29
  28  

which is probably not what you might expect at first.

See the provided reference for more information.

like image 72
Kevin Carrasco Avatar answered Sep 23 '22 20:09

Kevin Carrasco