I was learning when I found using modulo operator on a negative operator gives different output I was printing print(-28%10) which gave output 2 and print(28%-10) gave output as -2 what is the logic behind it as print(28%10) gave 8 as a result which is actual remainder. Can someone please help me understand this ??
            Asked
            
        
        
            Active
            
        
            Viewed 78 times
        
    3 Answers
1
            
            
        you can think of the A%B operator as a tool to: "add or substract B from A as long as we find a number that is between 0 and B" i.e.
-28%10 = 2
since:
-28 +10 +10 +10 = 2 # between 0 and 10
28%-10 = -2
since:
28 -10 -10 -10 = -2 #between 0 and -10
28 -10 -10 = 8 #not between 0 and -10
28%10 = 8
since:
28 -10 -10 = 8# between 0 and 10
 
    
    
        Nano Byte
        
- 106
- 3
1
            
            
        The % operator is in fact not the modulo operator but the remainder operator in python. The docs are not very clear about this but it does not follow the normal modulo logic for negative values instead simply getting the remainder.
 
    
    
        Exelian
        
- 5,749
- 1
- 30
- 49
0
            
            
        Guido van Rossum explains that he decided % would work this way, as this is useful for certain applications, for example if you are working with second-timestamps representing point in times before start of epoch (1 Jan 1970) you can easily compute number of days by doing t % 86400.
 
    
    
        Daweo
        
- 31,313
- 3
- 12
- 25
 
    