note
mugwumpjism
<p>Nice one. Your definition:</p>
<blockquote><i>"the intent of the modulus operator (x mod y) is to return the smallest number possible by repeatedly subtracting y from x."</i></blockquote>
<p>Clearly provides the behaviour expected by the poster of
this article. But who cares?</p>
<p>Any decision on what the function is or how it is defined
is arbitrary, and as other people have said, if you are
depending on nella's requested behaviour of mod, then you can always
just use a <code>( $y ? $x % $y : $x )</code> construct.</p>
<p>Most people are familiar with division, hence a modulus
is often explained as the remainer after dividing $x by $y.
This obviously is not correct for negative values of $x,
unless you count a negative remainder as being a value
subtracted from MAXINT (the modulus, in this case) in CS' two's
complement tradition.</p>
<p>If you take a definition from <a href="http://www.cut-the-knot.com/blue/Modulo.html">a random hit for "modulo mathematical definition" taken from the WWW</a>, for instance, you'll find the definition:</p>
<blockquote>Two numbers a and b are said to be equal or congruent
modulo N iff N|(a-b), i.e. iff their difference is exactly
divisible by N. Usually (and on this page) a,b, are
nonnegative and N a positive integer. We write a = b (mod N).</blockquote>
<p>Note that the difference has to be divisible by N.</p>
<p><a href="http://jacquardsystems.com/Examples/operator.htm#modulo">Another page</a> I found expressed it like this:
<blockquote>number % sub means: map the number on the left-hand side onto the subset {0,sub) (0, zero inclusive, sub exclusive). If sub is
negative, this should be (sub,0}, of course.</blockquote>
<p>Note the words "sub exclusive". Why, then would you map
the case where sub == 0 to {-infinity, infinity}? It doesn't follow the pattern.</p>
<p>Personally, I prefer to think of it in terms of what would
the last digit be if expressing this number in base $y?
Of course, I think of negative numbers in twos complement
form, and consider a negative modulus obfuscated programming (if I came across its use, I'd simply experiment to see what its behaviour was), so
this works for me :-)</p>
<p>Interestingly, C on my platform gets it wrong for negative
values of X and positive values of Y. I'm glad Perl doesn't.</p>
<p>ps. why would I want to read a book on number theory to
understand why a basic operator behaves the way it does?</p>
87384
88569