[docs] [issue14245] float rounding examples in FAQ are outdated

Zbyszek Szmek report at bugs.python.org
Sat Mar 10 19:21:26 CET 2012

Zbyszek Szmek <zbyszek at in.waw.pl> added the comment:

Proposed rewrite (building on Mark's version):
- mention C doubles
- explain ``1.2`` example a bit more

Why are floating-point calculations inaccurate?

Users are often surprised by results like this::

   >>> 1.2 - 1.0

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

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

   1.0011001100110011001100110011001100110011001100110011 (binary)

which is approximately::

   1.19999999999999995559 (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>

More information about the docs mailing list