Q:

Python Dictionary Floats

I came across a strange behavior in Python (2.6.1) dictionaries:
The code I have is:
new_item = {'val': 1.4}
print new_item['val']
print new_item

And the result is:
1.4
{'val': 1.3999999999999999}

Why is this?  It happens with some numbers, but not others. For example:

0.1 becomes 0.1000...001
0.4 becomes 0.4000...002
0.7 becomes 0.6999...996
1.9 becomes 1.8888...889

A:

This is not Python-specific, the issue appears with every language that uses binary floating point (which is pretty much every mainstream language).
From the Floating-Point Guide:

Because internally, computers use a format (binary floating-point)
  that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.
When the code is compiled or interpreted, your “0.1” is already
  rounded to the nearest number in that format, which results in a small
  rounding error even before the calculation happens.

Some values can be exactly represented as binary fraction, and output formatting routines will often display the shortest number that is closer to the actual value than to any other floating-point number, which masks some of the rounding errors.

