Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: the result of (8%3) is 2 but (-8%3) is 1. shouldn't it be -2? and why? [duplicate]

Tags:

python

Here is the proof:

-8 == -2 * 3 - 2

that means -8%3 should be equal to -2. but python returns 1 and it's driving me crazy

like image 935
Java Guy Avatar asked Dec 03 '22 20:12

Java Guy


2 Answers

In python, the sign matches the denominator.

>>> -8 % 3
1
>>> -8 % -3
-2

For an explanation of why it was implemented this way, read the blog post by Guido.

like image 131
wim Avatar answered Dec 05 '22 10:12

wim


integer math is funny:

>>> -8//3  # (-8/3 in python2 does the same thing)
-3
>>> 8//3   # (8/3 in python2 does the same thing)
2
>>>

Rounding is done down, not towards zero.

like image 29
mhlester Avatar answered Dec 05 '22 09:12

mhlester