This content has been marked as final. Show 9 replies
welcome to the world of floating point numbers
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
It's because 0.1 is periodic when you write it as a binary number. Try 0.5, 0.25, 0.125 and so on.
You probably want to use the BigDecimal class rather than Double.
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.
It's not the 1.1, 1.2 that's the problem. It's the .1 that you summed repeatedly in your first post
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.
Ah, Ok this makes things much clearer. Thanks for the help everyone.