[issue41920] Weird add operation of "0.2222 + 0.1111"

Steven D'Aprano report at bugs.python.org
Sat Oct 3 19:24:10 EDT 2020


Steven D'Aprano <steve+python at pearwood.info> added the comment:

Hi Leonard,

Any number which has only fixed precision will experience similar 
issues. It might affect different calculations.

In Python, float, complex and Decimal have fixed precision, so they can 
experience this issue.

But for simple calculations, Decimal may be better for you, as it uses 
base-10 floats, not base-2, so many numbers which are rounded off in 
binary floats are not rounded in Decimal:

    py> from decimal import Decimal
    py> 0.1111 + 0.2222  # binary floats
    0.33330000000000004
    py> Decimal('0.1111') + Decimal('0.2222')  # decimal floats
    Decimal('0.3333')

But with Decimal, you have other numbers which are rounded off and so 
are not exact:

    py> one_third = 1/Decimal(3)
    py> 3*one_third  # should be exactly 1
    Decimal('0.9999999999999999999999999999')

    py> (1/Decimal(6)) * 3
    Decimal('0.5000000000000000000000000001')

ints are always exact, but you can only do whole numbers with ints. 
Fractions are also exact:

    py> from fractions import Fraction
    py> Fraction(1111, 10000) + Fraction(2222, 10000)
    Fraction(3333, 10000)

Using Fraction is a good way to see what number a binary float really 
is:

    py> Fraction(0.1111)
    Fraction(4002799348806897, 36028797018963968)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41920>
_______________________________________


More information about the Python-bugs-list mailing list