[Tutor] modulo

Dave Angel d at davea.name
Mon Oct 8 01:07:15 CEST 2012

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)

Let's suppose we're talking about the days of the week, they repeat
every 7 days, so it's perfectly reasonable to do arithmetic modulo 7. 
Just considering the nonnegative numbers, we can take them as a strip,
and wrap them around a cylinder of circumference 7.  So 7, 14, and 21,
etc. wind up on top of 0, and they are all equal to zero, modulo 7. 
Likewise the 8, 15, 22, are congruent to 1, and so on.  That's the part
you said made sense.  One way to describe it is you subtract whatever
multiple of 7 you like, till you get to a value between 0 and 6.

So what about negative dividends? Instead of subtracting multiples of 7,
you add multiples of 7.  So if you have -5, you add 7 and you get 2.  -5
% 7  should yield 2, and it does.  If you consider that strip
representing the number line, and include the negative numbers as it's
wrapped around the cylinder, clearly -1 will line up with 6, and -2 with
5, and so on.

That's all informal.  More formally, there are two related operations,
the floor function and the mod function.  In Python there's a function
divmod() that gives you both results.  The relationship between the
floor, the modulo, the modulus (eg. 7) and the dividend is defined as:
     floor * modulus + modulo === dividend, and   modulo is between 0
and modulus-1, inclusive.

For negative modulus in python, I'd rather not go there, but I will if
you specifically ask.  And if you understood all the above.



More information about the Tutor mailing list