0

If you try the code here:

public class AddDecimalsMain {
public static strictfp void main(String[] args) {

    System.out.print("Default: "); 
    System.out.println(0.1 + 0.2);
    System.out.print("Float: "); 
    System.out.println(0.1F + 0.2F);
    System.out.print("Double: "); 
    System.out.println(0.1D + 0.2D);
}

}

you will get

Default: 0.30000000000000004
Float: 0.3
Double: 0.30000000000000004

Please do not give me the solution, I already know the solution is to use float, which is giving me the right addition, or better yet BigDecimal, I just want to understand why java's float arithmetic is more "accurate" than its default or double arithmetic in this very particular case.

Also if I change 0.2 to 0.1, or even 0.3, I seem to get the correct answer in all cases.

So if I add 0.1 + 0.1, I will correctly get 0.2 in all cases , I noticed this weird thing happens only when I add 0.1 + 0.2

I even tried strictfp in the method thinking this might make things accurate but it did not, again I'm trying to understand what is going on around here, not how to solve it.

I'm as confused as a boyscout.

stfudonny
  • 53
  • 1
  • 9
  • 1
    http://floating-point-gui.de/ ? –  Jul 21 '16 at 18:43
  • 3
    float is 32bit, double is 64bit. your values happen to evaluate to having a bunch of post-decimal zeroes that end being ALL zero in the 32bit representations, while 64bit has enough space to see that trailing `4`. – Marc B Jul 21 '16 at 18:43
  • Actually, it is because float have less precision than doubles that you have the correct result for `0.1f + 0.2f`, see also http://stackoverflow.com/questions/27598078/float-and-double-datatype-in-java – Tunaki Jul 21 '16 at 18:44
  • That does not explain why float is more accurate than double, if double has more room for precision. Also why is this strictly happening with 0.1+0.2, and not 0.1+0.1? or 0.2+0.2? – stfudonny Jul 21 '16 at 18:51
  • Thanks RC, I had no idea about this site! I think this answers my precise problem, I'm going to go through it all. – stfudonny Jul 21 '16 at 18:56
  • 3
    Float is not more accurate. The comparison is not exactly but conceptually similar to saying. "Why is 3.000004 closer to 3 when the precision is 3 significant digits, as opposed to when it's 6 significant digits. Shouldn't 6-significant digits be more accurate?". Well, it *is*, but the fact that it's more accurate also means it is more likely to show the inaccuracies at lower significant digits, whereas the 3-sig-digit one can't even express that kind of accuracy so it discards it, accidentally producing a more accurate number (because it happens that the right answer is 3) – Tasos Papastylianou Jul 21 '16 at 18:57
  • That explains it thanks Tasos. – stfudonny Jul 21 '16 at 19:00

0 Answers0