So... I just ran into a most peculiar problem as I was writing my program on my laptop, where it seemed like Java was bugging up on simple math with doubles (and floats, for that matter).
To make sure it wasn't just an environmental mistake on my laptop, I went to recreate the bug on my desktop pc.
For reference, I am using the NetBeans IDE 6.7.1 with the Java SE Development Kit 6 update 16.
First, I made a for-loop looking like this:
double result = 0;
for (double i = 0; i < 1; i += 0.1) {
result += 0.1;
System.out.println(result);
}
Then, to make sure it wasn't because of the for-loop, I wrote this instead:
double result = 0;
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
result += 0.1;
System.out.println(result);
In both situations, on both my computers, this is the output that I am getting:
run:
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
BUILD SUCCESSFUL (total time: 2 seconds)
That doesn't look right to me. In fact, it looks very wrong. And it's keeping me from writing a functional program.
Can anyone hint at what's going on here? Am I being really stupid and overseeing something?