Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Modulus Inconsistencies (Or Calling all Mathematicians)

by jonadab (Parson)
on Mar 27, 2003 at 01:50 UTC ( [id://246132]=note: print w/replies, xml ) Need Help??


in reply to Modulus Inconsistencies (Or Calling all Mathematicians)

The important thing about the modulus operator is that the results are consistent with integer division. i.e., if you divide the modulus by the divisor and add it to the result of integer division you get the actual quotient. In Perl, you can test that like this:

((($a%$b)/$b)+(int($a/$b)))==($a/$b)

I think I got that right. Anyway, you get the idea. The point of the modulus is that it gives you the correct amount of "left over", the amount by which integer division is off.

Some languages have a special integer division operator (usually spelled div), but AFAIK Perl doesn't, so the int truncation is the way integer division is done, then.

So I suspect that Perl has defined the mod operator (spelled %) in such a way as to keep the above assertion intact given the way int truncates. So the real question you want to ask is about why integer division is not consistent between all languages. Why do some langauges truncate down and others always truncate toward zero?

And I think the answer to that probably comes down to hysterical raisins, but I don't know the details.


for(unpack("C*",'GGGG?GGGG?O__\?WccW?{GCw?Wcc{?Wcc~?Wcc{?~cc' .'W?')){$j=$_-63;++$a;for$p(0..7){$h[$p][$a]=$j%2;$j/=2}}for$ p(0..7){for$a(1..45){$_=($h[$p-1][$a])?'#':' ';print}print$/}

Replies are listed 'Best First'.
Re: Modulus Inconsistencies (Or Calling all Mathematicians)
by jonadab (Parson) on Mar 27, 2003 at 02:01 UTC

    Forgot to mention: if I recall my study of equivalence classes in modern algebra correctly, the way Perl does this is the more mathematically correct way (because e.g., seven is equal to negative two modulo three IIRC; they are both in the 1 class). But that is far less imporant for programming purposes than getting the modulus consistent with int division, because all sorts of things will break if those aren't consistent. Whole algorithms would be untenable.


    for(unpack("C*",'GGGG?GGGG?O__\?WccW?{GCw?Wcc{?Wcc~?Wcc{?~cc' .'W?')){$j=$_-63;++$a;for$p(0..7){$h[$p][$a]=$j%2;$j/=2}}for$ p(0..7){for$a(1..45){$_=($h[$p-1][$a])?'#':' ';print}print$/}

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://246132]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2024-04-16 16:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found