[docs] [issue14245] float rounding examples in FAQ are outdated
Zbyszek Szmek
report at bugs.python.org
Sat Mar 10 21:10:12 CET 2012
Zbyszek Szmek <zbyszek at in.waw.pl> added the comment:
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.
"""
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue14245>
_______________________________________
More information about the docs
mailing list