Friday, August 08, 2008

Modulo differences

Should take more care when using modulo and negative numbers.
Did'nt expect a difference at first:




Excel=MOD(-1; 12) -> 11
Smalltalk (Squeak)-1 \\ 12 -> 11








Java-1 % 12 -> -1
VisualBasic-1 Mod 12 -> -1
(PL)SQLselect mod(-1, 12) from dual -> -1
JavaScriptalert(-1%12); -> -1

4 comments:

  1. Nice finding. i found this at http://mindprod.com/jgloss/modulus.html

    "In Java you take the remainder with the % operator. % is informally called the modulus operator, (sometimes called mod or modulo) though mathematicians and serious computer scientists would beg to differ, it is a remainder operator not a modulus. The JLS correctly refers to it as a remainder operator."

    the Java language Spec really call the operator remainder not modulus as the quoted text indicates. I tested on VisualAge Smalltalk with the same behavior than Squeak (but the documentation call it remainder and not modulus). Squeak has no documentation for this.

    The latest free available draft of ANSI Smalltalk call the \\ a remainder too, based on the definition on ISO/IEC 10967, I have no access to it :-( (why standard specs must be purchased???)

    http://en.wikipedia.org/wiki/Modulo_operation has a table of how it works on different languages

    it will be interesting to know which are the reasons, something more precise than:

    "what exactly constitutes the result of a modulo operation depends on the programming language and/or the underlying hardware"

    I am thinking Excel and Smalltalk use the ANSI definition, and Java tried to be compatible with previous languages (SQL, COBOL) or the initial Java target hardware (embedded devices) where the reason.

    Thanks for sharing this interesting finding

    ReplyDelete
  2. On all of the schemes I have available (PLT, Chicken, and Gauche) (modulo -1 12) => 11

    In Gnu Smalltalk I also get 11. On Syx (version 0.1.6 is all I have installed for some reason) the answer is -1.

    ReplyDelete
  3. Hi, don't forget you have another modulo in Smalltalk: check #rem:

    quo: and rem: are alternative to // and \\ behaving more like Java/C (fmod)/FORTRAN (MOD) etc...

    To add confusion, Matlab has rem implemented as Smalltalk \\, and mod implemented as Smalltalk #rem:

    ReplyDelete
  4. should also note that "x mod y" where x<y gives x

    ReplyDelete