This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author zbysz
Recipients docs@python, loewis, mark.dickinson, zbysz
Date 2012-03-10.20:10:11
SpamBayes Score 0.0
Marked as misclassified No
Message-id <4F5BB51B.6050602@in.waw.pl>
In-reply-to <4F5BA2E0.80900@v.loewis.de>
Content
On 03/10/2012 07:52 PM, Martin v. Löwis wrote:
>> - explain ``1.2`` example a bit more
>
> +1 for giving the binary representation; -1 for rounding
> the decimal version of it.

Oh, 1.1999999999999999555910790149937383830547332763671875
is exactly equal to 
1.0011001100110011001100110011001100110011001100110011. In this case 
yes, rounding it is not beneficial.

So one more version (without this rounding):

"""
Why are floating-point calculations inaccurate?
-----------------------------------------------

Users are often surprised by results like this::

    >>> 1.2 - 1.0
    0.199999999999999996

and think it is a bug in Python.  It's not.  This has little to do with 
Python, and much more to do with how the underlying platform handles 
floating-point numbers.

The float type in CPython simply uses C ``double`` for storage. The 
number is stored in binary floating-point with a fixed precision 
(typically 53 bits) and Python uses C operations, which in turn rely on 
the hardware implementation in the processor, to perform floating-point 
operations. This means that as far as floating-point operations are 
concerned, Python behaves like many popular languages including C and Java.

Many numbers that can be written easily in decimal notation (``1.2``, 
for example), cannot be expressed exactly in the binary format.  After::

    >>> x = 1.2

the value stored for ``x`` is a (very good) approximation of the value 
``1.2``, but is not exactly equal to it.  On a typical machine, the 
actual stored value is::

    1.0011001100110011001100110011001100110011001100110011 (binary)

which is exactly::

    1.1999999999999999555910790149937383830547332763671875 (decimal)

53 binary digits are equivalent to about 16 decimal digits and in this 
case the first 17 digits are correct after the conversion back to decimal.

Similarly, the result of any floating-point operation must be rounded to 
fit into the fixed precision, often resulting in another tiny error.

For a more detailed explanation of what's involved, please see the 
chapter on :ref:`floating point arithmetic <tut-fp-issues>` in the 
Python tutorial.
"""
History
Date User Action Args
2012-03-10 20:10:12zbyszsetrecipients: + zbysz, loewis, mark.dickinson, docs@python
2012-03-10 20:10:11zbyszlinkissue14245 messages
2012-03-10 20:10:11zbyszcreate