Perl: the Markov chain saw  
PerlMonks 
Re: Re: Re: 0 illegal modulus?by mugwumpjism (Hermit) 
on Jun 15, 2001 at 00:20 UTC ( #88604=note: print w/replies, xml )  Need Help?? 
Nice one. Your definition: "the intent of the modulus operator (x mod y) is to return the smallest number possible by repeatedly subtracting y from x." Clearly provides the behaviour expected by the poster of this article. But who cares? 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 ( $y ? $x % $y : $x ) construct. 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. If you take a definition from a random hit for "modulo mathematical definition" taken from the WWW, for instance, you'll find the definition: Two numbers a and b are said to be equal or congruent modulo N iff N(ab), 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). Note that the difference has to be divisible by N. Another page I found expressed it like this: number % sub means: map the number on the lefthand side onto the subset {0,sub) (0, zero inclusive, sub exclusive). If sub is negative, this should be (sub,0}, of course. Note the words "sub exclusive". Why, then would you map the case where sub == 0 to {infinity, infinity}? It doesn't follow the pattern. 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 :) Interestingly, C on my platform gets it wrong for negative values of X and positive values of Y. I'm glad Perl doesn't. ps. why would I want to read a book on number theory to understand why a basic operator behaves the way it does?
In Section
Meditations

