The modulo operation on negative numbers in Python

前端 未结 8 1937
无人共我
无人共我 2020-11-22 14:26

I\'ve found some strange behaviour in Python regarding negative numbers:

>>> -5 % 4
3

Could anyone explain what\'s going on?

8条回答
  •  独厮守ぢ
    2020-11-22 14:44

    It's also worth to mention that also the division in python is different from C: Consider

    >>> x = -10
    >>> y = 37
    

    in C you expect the result

    0
    

    what is x/y in python?

    >>> print x/y
    -1
    

    and % is modulo - not the remainder! While x%y in C yields

    -10
    

    python yields.

    >>> print x%y
    27
    

    You can get both as in C

    The division:

    >>> from math import trunc
    >>> d = trunc(float(x)/y)
    >>> print d
    0
    

    And the remainder (using the division from above):

    >>> r = x - d*y
    >>> print r
    -10
    

    This calculation is maybe not the fastest but it's working for any sign combinations of x and y to achieve the same results as in C plus it avoids conditional statements.

提交回复
热议问题