Search code examples
pythonlanguage-lawyer

Why does the floordiv (//) opertor with python decimals round toward 0 instead of negative infinity?


>>> import decimal
>>> decimal.Decimal(-7) // 4
Decimal('-1') # Result rounded towards 0.
>>> -7 // 4
-2  # Result rounded towards negative infinity.

Why does the floordiv operator with a python decimal round towards 0 instead of towards negative infinity, as the floordiv operator does with all other types?


Solution

  • From BPO-12005 (formatting mine):

    The specification on which the decimal module is based requires that there be a 'remainder' operation with the semantics of Decimal's % operation (i.e., the result of x % y has the sign of x). However, the specification doesn't say anything about how the prescribed operations should map to language constructs.

    So the choice was between (1) leaving % for Decimal objects unimplemented, and providing a separate 'remainder' method, or (2) mapping % to Decimal's remainder operation, and accepting the slight mismatch between the % semantics for float and Decimal.

    Perhaps the wrong choice was made. But it's there now, and to me it's not so obviously wrong that it's worth the upheaval of deprecating % for Decimal objects.

    Mark Dickinson (May 5, 2011)

    The post above is about %, but this also applies to //.