Python remainder operator

Is there any remainder operator in Python? I do not ask the modulo operator, but the rest. For instance:

-5 mod 2 = 1 

but

 -5 rem 2 = -1 # where "rem" is a remainder operator. 

Should I implement it myself;)?

+6
source share
3 answers

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 .. .).

+18
source

Edit: it is not entirely clear what you had in mind when you asked for the remainder operation, the way to do this will depend on what requirements exist in the output sign.

If the sign is always a positive divmod can do what you want, it is in the standard library

http://docs.python.org/2/library/functions.html#divmod

You can also look at the built-in binary arithmetic operators:

http://docs.python.org/2/reference/expressions.html

If the rest should have the same sign as the argument you passed, you will have to flip it, for example:

 import math def rem(x,y): res = x % y return math.copysign(res,x) 
+1
source

Does math.fmod do what you are looking for?

-1
source

Source: https://habr.com/ru/post/952699/


All Articles