[Nathan Levett <nathan.levett...@gmail.com>]
> First time posting here ~ I've recently encountered that python does not
> have an OOTB operator for modulo that is consistent with Euclidean
> division.

You need to be very explicit about what you intend - my best guess
about what you intend isn't supported directly by any programming
language I'm aware of.

Most languages have notions of "integer division" (intdiv) and
"integer modulus" (intmod) connected by this identity when the divisor
(`b`) isn't 0:

    a = intdiv(a, b) * b + intmod(a,, b)

That's so in Python too. Pick what you want intdiv to do, and the
meaning of intmod is forced to match. Likewise you can pick what
intmod should do, and that forces the meaning of intdiv.

Most languages pick "I want intdiv(a, b) to return the infinitely
precise value a/b, truncated to the integer closest to 0". While
"classic C" didn't ;require that, the current C standards do.

As a result, "a % b" in current C has the same sign as `a`.

Python much wanted instead for intmod(a, b) to be >= 0 whenever b > 0.
IOW, for intmod(a, b) to have the same sign as `b`. That corresponds
to intdiv(a,b) returning the floor of the infinitely precise a/b.

Another choice is made by math.remainder:

>>> import math
>>> math.remainder(7, 10)
-3.0

That's required by some standards, and corresponds to rounding the
infinitely precise a/b to the closest integer (which in turn
corresponds to intmod returning the element of a's modular equivalence
class with minimum absolute value).

What I'm _guessing_ you mean by "Euclidean division" is that

    0 <= divmod(a,b) < abs(b)

That is, the modulus is always non-negative, regardless of the inputs' signs.

I expect no languages implement that because: (a) there's no
particularly compelling use for it ;-) ; and, (b) it leads to a
strained definition of intdiv ("return the floor of a/b if b > 0, but
return the ceiling of a/b if b < 0).

> ..;.
> Keen to know how open y'all're to it!

I'm not. I've done a fair amount of number-theory-ish stuff in Python,
and can't recall ever having a use for it. I've VERY often relied on
that a%b is non-negative when b > 0, but have almost never had a real
use for a negative modulus (`b`).
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ELS5BNEDMYY37N2VUXGWGGYHWUHYHL2J/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to