I have aproblem with long sums of floats or doubles in Java.
If I execute:
for ( float value = 0.0f; value < 1.0f; value += 0.1f )
System.out.println( value );
I get:
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001
How do I get rid of the accumulation of the floating precision error?
I tried using doubles to halve the error, but the result is the same.
There is a no exact representation of 0.1 as a
floatordouble. Because of this representation error the results are slightly different from what you expected.A couple of approaches you can use:
doubletype, only display as many digits as you need. When checking for equality allow for a small tolerance either way.BigDecimalcan represent 0.1 exactly.Example code for
BigDecimal:See it online: ideone