In fact, there are three different definitions of "modulo" or "remainder", and not two:
- Truncated remainder of division: the sign coincides with the dividend.
- Balance based on floating division: the sign matches the divisor.
- The remainder of the Euclidean division: the sign is always positive.
The call of one of them is “modulo”, and the other “remainder” is very confused; all three of them are useful definitions for both terms.
Almost every language provides only one of three (Fortran is a notable exception). * Most languages provide one that matches the language separation operator. ** Since Python uses gender separation (after the Knuth argument in Art of Computer Programming), it uses the appropriate remainder operator.
If you want any other, you must write it manually. It is not very difficult; this wikipedia article shows how to implement all three.
For instance:
def trunc_divmod(a, b): q = a / b q = -int(-q) if q<0 else int(q) r = a - b * q return q, r
Now for your example:
>>> q, r = trunc_divmod(-5, 2) >>> print(q, r) -2 -1
* Often languages that promise a truncated remainder have some variations on mod and impose some changes on rem ... but there is definitely nothing to rely on. For example, Fortran calls the remainder of modulo , and the circuit calls the Euclidean remainder mod .
** Two notable exceptions: C90 and C ++ 03, which leave a choice before implementation. While many implementations use truncated divisions and residues, some of them (some do not even use truncated division and remain on the floor, which means that a = b * (a/b) + a%b does not even work .. .).
source share