0

In Java I am trying to graph points, and the distance between each point is pretty small (0.002).

However when I graphed my data I noticed there were 'holes' in the graph where the line stopped then continued again a bit further.

So, I started to print out the X value and I noticed it being an insane amount of decimal points longer than it should be.

It should only be multiples of .002 but instead you have numbers like:

1.1740000000000008

Which if you by hand continuously added .002 to itself you would never get that number.

So, I put together this abstract of code to just print out Java adding two doubles together and it's output shows what is going wrong.

public class Test {

    public static void main(String[] args) {
        Double rate = 0.002;

        for (double x = 0.0; x < 60; x += rate) {
            System.out.println("X: " + x + " --- Rate: " + rate);
        }
    }
}
  • X: 0.0 --- Rate: 0.002
  • X: 0.002 --- Rate: 0.002
  • X: 0.004 --- Rate: 0.002
  • X: 0.006 --- Rate: 0.002
  • X: 0.008 --- Rate: 0.002
  • X: 0.01 --- Rate: 0.002
  • X: 0.012 --- Rate: 0.002
  • X: 0.014 --- Rate: 0.002
  • X: 0.016 --- Rate: 0.002
  • X: 0.018000000000000002 --- Rate: 0.002
  • X: 0.020000000000000004 --- Rate: 0.002
  • X: 0.022000000000000006 --- Rate: 0.002
  • X: 0.024000000000000007 --- Rate: 0.002

As you can see on the 9th time of adding .002 it instead adds 0.002000000000000002 instead, then later on only .002000000000000001.

Can anyone explain this to me? And how I should go about fixing it.

Dylan Holmes
  • 335
  • 1
  • 6
  • 17

0 Answers0