Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Calculations returning wrong answer? [duplicate]

Tags:

java

Possible Duplicate:
Retain precision with Doubles in java
Moving decimal places over in a double

For example, something as simple as this:

public class WrongAnswer {
  public static void main(String[] args) {
    System.out.println(100*1.1);
  }
}

prints 110.00000000000001 instead of 110. Using other numbers instead of 100*1.1 also give a lot of digits with some random digit at the end that isn't right..

Any ideas?

like image 541
Nate Avatar asked Oct 22 '12 21:10

Nate


2 Answers

Floating point notations have limited degrees of accuracy. Here's a guide: http://floating-point-gui.de/

like image 118
CookieOfFortune Avatar answered Nov 09 '22 23:11

CookieOfFortune


Most floating point calculations involve rounding errors. In your case, there are two rounding errors: converting (decimal) 1.1 to floating point (there's no exact representation for 1.1 in IEEE 754 floating point--which is what Java uses) and then multiplying by 100. See the excellent article What Every Computer Scientist Should Know About Floating-Point Arithmetic for more info.

like image 41
Ted Hopp Avatar answered Nov 10 '22 00:11

Ted Hopp