There should be only one answer for identical operations. But seems like the Python built-in numeric type and the decimal
module are contradicting on modulo operator.
The documentation on the modulo operator says:
The modulo operator always yields a result with the same sign as its second operand (or zero)
So this behavior is expected:
>>> -45 % 360
315
But the decimal
operator seems to be doing the opposite. That is, it yields a result with the same sign as its first operand.
>>> from decimal import Decimal
>>> Decimal('-45') % 360
Decimal('-45')
If you dig a little deeper, you can find:
>>> -45/360
-0.125
>>> -45//360
-1
>>> Decimal('-45')/360
Decimal('-0.125')
>>> Decimal('-45')//360
Decimal('-0')
While the floor division
is taking the floor in -45//360
, it's taking the ceil
in Decimal('-45')//360
.
Why different behavior for identical operations? This can throw someone in trouble if s/he is not conscious about it.
There is a discussion in Modulo operation on a python negative decimal.Decimal and a positive int But I couldn't get the fact why there are two different approaches?