i am kind of confused why python add some additional decimal number in this case, please help to explain
>>> mylist = ["list item 1", 2, 3.14]
>>> print mylist ['list item 1', 2, 3.1400000000000001]
i am kind of confused why python add some additional decimal number in this case, please help to explain
>>> mylist = ["list item 1", 2, 3.14]
>>> print mylist ['list item 1', 2, 3.1400000000000001]
We can fix it by this command:
I add an answer from @mark
It is worthwhile to note that Python 3.1 has a new floating point output routine that rounds this in the expected manner (it has also been backported to Python 2.7):
From the What's New in Python 3.1 document:
Floating point numbers are an approximation, they cannot store decimal numbers exactly. Because they try to represent a very large range of numbers in only 64 bits, they must approximate to some extent.
It is very important to be aware of this, because it results in some weird side-effects. For example, you might very reasonably think that the sum of ten lots of
0.1
would be1.0
. While this seems logical, it is also wrong when it comes to floating point:You might think that
n / m * m == n
. Once again, floating-point world disagrees:Or perhaps just as strangely, one might think that for all
n
,n + 1 != n
. In floating point land, numbers just don't work like this:See What every computer scientist should know about floating point numbers for an excellent summary of the issues.
If you need exact decimal representation, check out the decimal module, part of the python standard library since 2.4. It allows you to specify the number of significant figures. The downside is, it is much slower than floating point, because floating point operations are implemented in hardware whereas decimal operations happen purely in software. It also has its own imprecision issues, but if you need exact representation of decimal numbers (e.g. for a financial application) it's ideal.
For example:
As mentioned before, it's all about floating points being an approximation.
If you want exactness you can use a decimal (which is a precise representation): http://docs.python.org/library/decimal.html