0

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?

Fahim
  • 308
  • 1
  • 3
  • 10
  • Unfortunately, no. The accepted answer says, >"As for why the Decimal Specification goes on this route, instead of doing it like in math where the remainder is always positive, I'm speculating that it could be for the simplicity of the subtraction algorithm." But my question is why they are taking two different approaches? – Fahim Sep 26 '20 at 16:47
  • 1
    Only the original authors can answer why they choose the approach they did. Guido van Rossum chose to use floor division as explained in his blog post "[Why Python's Integer Division Floors](http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html)" and the authors of the Decimal module chose to follow IBM’s General Decimal Arithmetic Specification. – Craig Sep 26 '20 at 17:36

0 Answers0