The modulo operation on negative numbers in Python

前端 未结 8 1867
无人共我
无人共我 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:59

    I also thought it was a strange behavior of Python. It turns out that I was not solving the division well (on paper); I was giving a value of 0 to the quotient and a value of -5 to the remainder. Terrible... I forgot the geometric representation of integers numbers. By recalling the geometry of integers given by the number line, one can get the correct values for the quotient and the remainder, and check that Python's behavior is fine. (Although I assume that you have already resolved your concern a long time ago).

    0 讨论(0)
  • 2020-11-22 15:01

    In python, modulo operator works like this.

    >>> mod = n - math.floor(n/base) * base
    

    so the result is (for your case):

    mod = -5 - floor(-1.25) * 4
    mod = -5 - (-2*4)
    mod = 3
    

    whereas other languages such as C, JAVA, JavaScript use truncation instead of floor.

    >>> mod = n - int(n/base) * base
    

    which results in:

    mod = -5 - int(-1.25) * 4
    mod = -5 - (-1*4)
    mod = -1
    

    If you need more information about rounding in python, read this.

    0 讨论(0)
提交回复
热议问题