Java Can’t Add

So I’ve got a simple little loop I need for a new tool in my Ardustat GUI that basically does this

  • Take a number (e.g. 1)
  • Increment that number by a fixed amount (e.g. 0.01)
  • Loop recursively till it hits a declared end point (e.g. 3)

Easy right?

Looks something like this in java:

    public class javatest 
    {
        public static void main(String args[])
        {
            double start = 1;
            double inc = .01;
            double end = 3;
            double atnow = start;
            while (atnow < end)
            {
                atnow = atnow + inc;
                System.out.println(atnow);
            }
        }
    }

Right? Not so much.

The output should read

1.01
1.02
1.03
1.04
1.05
1.06
1.07
1.08
1.09
1.1
1.11
1.12
......
2.99
3

But instead I get

1.01
1.02
1.03
1.04
1.05
1.06
1.07
1.08
1.09
1.1
1.11
1.12
1.1300000000000001
1.1400000000000001
1.1500000000000001
1.1600000000000001
1.1700000000000002
1.1800000000000002
1.1900000000000002
...
2.9199999999999813
2.929999999999981
2.939999999999981
2.9499999999999806
2.9599999999999804
2.96999999999998
2.97999999999998
2.98999999999998
2.9999999999999796
3.0099999999999794

What gives? This is on my Intel Mac, running OS X 10.4.10. My copy of XP, running virtualized through Parallels does the same.

Float does the same thing.

There’s a very unsatisfying answer here, where there is some talk of how java handles doubles, and how you essentially have to round these things off. Sounds like the bank heist scam in office space or superman III.