[issue46639] Ceil division with math.ceildiv

Tim Peters report at bugs.python.org
Tue Feb 8 01:05:10 EST 2022


Tim Peters <tim at python.org> added the comment:

The `decimal` module intends to be a faithful implementation of external standards. The identity

x == (x // y) * y + x % y

isn't a minor detail, it's the dog on which all else is but a tail ;-)

It's why Guido picked -7 // 4 = -2 in Python[1]. That's really not all that useful on its own, and does surprise people. But it's necessary so that the identity implies -7 % 4 = 1, and _that's_ what drove it all, the desire that doing mod wrt a positive int always give a non-negative result.

The identity also implies that, under truncating division, mod returns a result with the sign of the dividend rather than of the divisor.

`decimal` implements what the external standards demand integer division do, and also integer modulus. The decimal context `divmod()` method returns both at once.

The behavior of int div and mod are linked by all standards I'm aware of, including by C89 (which didn't define what integer division did in all cases, but did demand that - whatever it did - % had to work in a way consistent with the named identity).

[1] http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html

----------

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


More information about the Python-bugs-list mailing list