9 Replies Latest reply on Nov 9, 2007 1:04 AM by 807603

    Double Precision Problems...

    807603
      Can anyone explain the output of the following code to me? I don't understand why there is a precision issue here. The desired result is what you would get if you used a calculator to increment 1.0 by 0.1 over and over again (i.e. 1.1, 1.2, 1.3, 1.4, 1.5...).

      Code:

      double a = 1.0;
      double b = 2.0;
      double i = 0.1;

      for (double n = a; a <= b; a += i) {
      System.out.println("a: " + a);
      }

      Output:

      a: 1.0
      a: 1.1
      a: 1.2000000000000002
      a: 1.3000000000000003
      a: 1.4000000000000004
      a: 1.5000000000000004
      a: 1.6000000000000005
      a: 1.7000000000000006
      a: 1.8000000000000007
      a: 1.9000000000000008

      I have pretty much the same problem if I use all floats also.