IanusKeddy
IanusKeddy

Reputation: 19

Why does python show 0.2 + 0.2 as 0.4?

I think I understood why 0.1 + 0.2 is 0.30000000000000004, but following the same logic why is 0.2 + 0.2 = 0.4? Isn't 0.2 a value you can't get in binary base? Thank you for your time.

Upvotes: 1

Views: 948

Answers (1)

jcoppens
jcoppens

Reputation: 5440

To get 0.2 you need to sum binary fractions of 2. Here are the first few:

Decimal   Binary
1       = 1
0.5     = 0.1
0.25    = 0.01
0.125   = 0.001
0.0625  = 0.0001

So, to get 0.2, you need to sum

0.125
+ 0.0625 = 0.187500

The next binary fraction is 0.03125. If I sum that, it's too large (> 0.2), so is the next one 0.015625. The following one, 0.0078125 is ok, so

0.125 + 0.0625 + 0.0078125 = 0.195312

and so on. So we have skipped 0.5 (gives a 0), and 0.25 (another 0), we did use 0.125 (1) and 0.0625 (1). Again, we skipped two values (00) and used the next one (1)...

But, whatever we do, we cannot represent 0.2 with an exact binary numner. we have to continue and continue... If we don't continue infinitely, the representation is not exactly 0.2...

Now try with 0.25 or 0.25...

Now why are we seeing different things in modern Pythons (>= 2.7, and >= 3), this comes from an internal change:

In versions prior to Python 2.7 and Python 3.1, Python rounded this value to 17 significant digits, giving ‘0.10000000000000001’. In current versions, Python displays a value based on the shortest decimal fraction that rounds correctly back to the true binary value, resulting simply in ‘0.1’.

See this article, bottom of the page.

Upvotes: 2

Related Questions