2

Modulo operator % on negative numbers is implemented in different way in python and in C. In C: -4 % 3 = -1, while in python:-4 % 3 = 2.

I know how to implement python-like modulo in C. I wonder how to do the reverse, that is: easily implement a C-like modulo in python.

sygi
  • 4,557
  • 2
  • 32
  • 54
  • 1
    Depending on the C compiler, environment you will get different result for negative modulo. – falsetru Dec 15 '15 at 14:29
  • 5
    Use brackets `- (4 % 3)` – Bhargav Rao Dec 15 '15 at 14:30
  • 1
    This is the old div/mod rem/quot debate. TL;DR: Different processors implement this differently thus different languages permit different semantics. – fuz Dec 15 '15 at 14:47
  • Yup. Tabs/spaces V2.0 – Martin James Dec 15 '15 at 14:55
  • 1
    @BhargavRao *Use brackets `- (4 % 3)`* That doesn't apply if the original `-4` and `3` values are variables and not hardcoded constants. For example: `int k = i % j`, given `int i = -4` and `int j = 3`. – Andrew Henle Dec 15 '15 at 15:13
  • @AndrewHenle [Operator](https://docs.python.org/3/reference/expressions.html#evaluation-order) [Precedence](http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm) is the culprit. :-) – Bhargav Rao Dec 15 '15 at 15:26
  • 1
    @BhargavRao *Operator Precedence is the culprit. :-)* No. This has nothing to do with operator precedence. There is no negation operator in `int k = i % j;` given `int i = -4; int j = 3;` – Andrew Henle Dec 15 '15 at 15:38
  • 1
    There was a discussion going on about this at http://bugs.python.org/issue22477 – Dschoni Dec 21 '16 at 16:29

2 Answers2

3

easily implement a C-like modulo in python.

Since C does truncation toward zero when integers are divided, the sign of the remainder is always the sign of the first operand. There are several ways to implement that; pick one you like: def mod(a, b): return abs(a)%abs(b)*(1,-1)[a<0] def mod(a, b): return abs(a)%abs(b)*(1-2*(a<0))

Armali
  • 18,255
  • 14
  • 57
  • 171
0

Just add the modul to the result if it's negative:

int mymod(int a, int b) {
   int res = a % b;
   if (res < 0)
      res += b;
   return res;
}

EDIT: and the other way round:

def mymod(a, b):
    res = a % b
    if (a < 0):
        res -= b
    return res
Ctx
  • 18,090
  • 24
  • 36
  • 51