Modulo Operator

Hi all

I found this and could you tell me what I missed

1 
result = 10 % 3
print(result)  # Output: 1 

2
result = 7 % -3
print(result)  # Output: -2

as according to the math in second code I'll get the same output as in first one

so 7 -> 3*2 -> 6 and 7- 6 = 1 and not -2

3 comments · 84% upvoted · other discussions

comments

jddddddddddd

https://stackoverflow.com/questions/5584586/find-the-division-remainder-of-a-number

That % operator returns the true modulus. This is why some languages have a mod and a rem operator.

Have a look at math.remainder()

import math

result1 = 7 % -3
print(f"mod = {result1}")

result2 = math.remainder(7, -3)
print(f"remainder = {result2}")

Outputs..

mod = -2
remainder = 1.0
QuarterObvious

Integer division always rounds the result toward a smaller integer number.

So 7//3 will be 2, but 7//-3 will be -3. Because of this there is a difference in modulo.

JamzTyson

Python uses floored division to calculate the modulo:

div = 7 // -3  # -3
mod = 7 - (-3 * div)  # -2

There is a detailed description HERE