I've read this Stack Overflow thread, and this blog post, but am still unable to understand why some floating point numbers can be represented exactly in binary, and why some can't.
I understand that 0.1
, 0.2
, 0.3
, 0.4
, 0.6
, 0.7
, 0.8
, 0.9
will give an infinite fraction in the binary system as their denominators, since neither 10 nor 5 can be represented with powers of two. 0.5
however has a denominator of 2^1
.
When I add 0.2 + 0.4
, I get 0.6000000000000001
, when I add 0.1 + 0.5
, I get 0.6
. I thought this was because, in the first sum, I was adding two infinite fractions, whereas, in the second sum, I was adding with 0.5
, which has a finite representation, with 0.1
, which doesn't. However, when I add 0.3 + 0.4
, I get 0.7
, which I didn't expect, considering both 0.3
and 0.4
do not have exact representations, and nor does 0.7
.
I would have thought that since 0.5
is the only decimal from 0.1
to 0.9
(at only one decimal place) with a finite representation, working with any other decimals would give a non-exact representation, but this is not the case.
Why do adding some one point decimals with no finite representation in binary yield an exact representation and some not?