The other day i was testing a system that calcuates weights and i discobered a precision bug in Java.
Try to run this:
public void testPor3(){
double a = 3;
double b = a * 0.2;
System.out.println(b);
double af = 3;
double bf = a / 5;
System.out.println(bf);
}
The output that i got was:
0.6000000000000001
0.6
Then, i and Fede googled about this error and we found this (http://www.velocityreviews.com/forums/t139008-java-double-precision.html):
double val = 0;
for(int i=0;i<10;i++) {
val+=0.1;
System.out.println(val);
}
has the following (terrible) output:
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
for(int i=0;i<10;i++) {
val+=0.1;
System.out.println(val);
}
has the following (terrible) output:
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
What a mess!
By the way, If someone knows how to solve this precision problem, please let me know, because I need to calculate weights with this precision...
ReplyDeleteThat's a natural result from using IEEE 754 floating point numbers. Basically, some decimal fractions cannot be exactly represented using binary fractions. It's like trying to represent 1/3: it'd be "0,333..." in base 10, but only "0,1" in base 3 (1*3^{-1}).
ReplyDeleteIf you're that concerned about getting exact results, use BigDecimal instead of a regular float. BigDecimal guarantees that things like 0.1 + 0.1 really produce 0.2 and not 0.19999 or 0.200001.
Here's an example. Try running it :-).
ReplyDeletehttp://pastebin.com/59c22AdZ