[Tutor] modulo

Dave Angel d at davea.name
Mon Oct 8 01:24:22 CEST 2012


On 10/07/2012 07:16 PM, Oscar Benjamin wrote:
> On 8 October 2012 00:07, Dave Angel <d at davea.name> wrote:
>> On 10/07/2012 06:49 PM, Esteban Izaguirre wrote:
>>> Hi, I'm following coursera's learn to program: the fundamentals, which
>>> teaches programming basics in python. Our first assignement involves the
>>> modulo operator with a negative divident, and while I've managed to get to
>>> understand it enough for the purposes of the assignement with help from
>>> othe rstudents, I still don't know how the hell it works, I wouldn't know
>>> how to use modulo in another situation if it ever arised. So, i undertand
>>> how modulo works when only positive numbers are used, but how does modulo
>>> determine, that, say -15 % 14 is equal to 13? Or -20 % 100 is 20? I just
>>> don't get how modulo works, all explanations I've found online only seem to
>>> be in relation of how this applies to perl or something, can someone
>>> explain it to me?
>>>
>>>
>>
>> There is one perfectly reasonable definition for how modulo should
>> behave if the denominator (modulus) is positive. Python does it 'right',
>> so I'll try to explain it in a couple of ways.
>>
>> (If the modulus (denominator) is negative, it makes no sense to me, so I
>> can't even recall what Python does, and I have to look it up each time.
>> Fortunately this is rare, and in my code, I just avoid it)
> 
> The sign of the modulo operation is always the same as the sign of the
> denominator:
> 
> 
>>>> 3%5
> 3
>>>> 3%(-5)
> -2
>>>> (-3)%5
> 2
>>>> (-3)%(-5)
> -3
> 
> 
> That way you can say that the result of the a % b is always in the
> range from 0 to b (not including b itself).
> 
> 

It still makes no sense to me.  There are at least two equally silly
ways to define the results of a negative modulus, and you've properly
described one of them, presumably the one that Python implements.

But I've used and abused about 35 languages over the years, and each
makes its own choice for this.  I'd rather just call it undefined, and
eliminate it.  That's what we did when the hardware guys couldn't decide
how the hardware was going to respond to a particular microcode bit
pattern.  They documented it as undefined, and I made it illegal in the
microcode assembler.

Fortunately, the OP isn't asking about this case, which is the other
reason I didn't bother to describe what Python does.



-- 

DaveA


More information about the Tutor mailing list