This content has been marked as final. Show 9 replies
It's just how the IEEE floating point standard works - many relatively simple numbers do not have an exact representation in the IEEE standard. You could display the numbers in a different format which would remove the annoying extra digits...
Output should be:
import java.text.DecimalFormat; /... static DecimalFormat df = DecimalFormat("0.000"); //loop System.out.println("a: " + df.format(a));
Edited by: practissum on Nov 8, 2007 12:08 PM
Thanks for the replies. I had suspected the problem was what practissum mentioned above: That there isn't an exact representation for those numbers (1.2, 1.3, etc) in the IEEE standard. But if that is the case, how do you explain the following:
double d0 = 1.1; double d1 = 1.2; double d2 = 1.3; System.out.println("d0: " + d0); System.out.println("d1: " + d1); System.out.println("d2: " + d2);
So it's something that has to do with the arithmetic operations being done on the numbers. I expect this kind of thing for very small numbers, not things like 1.1.
It should also be noted that I'm not concerned with how the numbers look when I print them out. I'm concerned with the actual internal representation.
P.S. jToohey, thanks for the link. Working my way through that document.
mjs483 wrote:They don't have to be small. 0.1 doesn't give you exact results in your first example, while for example 0.03125 would be ok even after many additions. That's because 0.03125 has a non-periodic binary representation (0.00001) so its repeated use is safe.
I expect this kind of thing for very small numbers, not things like 1.1.
Numbers like 1.2 or 1.3 are ok if you don't repeatedly add them to something.