[Tutor] The remainder %
Karl Pflästerer
sigurd@12move.de
Tue Jun 3 16:05:03 2003
On 3 Jun 2003, Bob Gailer <- bgailer@alum.rpi.edu wrote:
> In math modulo is NOT the same as remainder. At least the explanation
> says "remainder". Modulo and remainder have the same values when the
> left argument is >= 0, and different values for < 0. Example:
> n n modulo 3 n % 3
> 3 0 0
> 2 2 2
> 1 1 1
> 0 0 0
> -1 2 1
> -2 1 2
> -3 0 0
Some time ago I had nearly the same discussion (the subject was: how
exactly is modulo in math defined); it turned out that there is no
definition for modulo which returnes *one* number. Modulo describes
something which in german is called `Restklasse' (residue class).
So it's up to the implementor of the function in the particular language
how he defines modulo.
> The only programming language I know that "got is right" is APL. There
> the function is named modulo and it DOES modulo. Most other languages
> call it modulo and it does remainder.
I am sure that Common Lisp does it `right' and I think Ada also (modulo
the multiple possibilities to define modulo :-))
$ clisp
[1]>
(format t
"+5 modulo +3 = ~A ~@
+5 modulo -3 = ~A ~@
-5 modulo +3 = ~A ~@
-5 modulo -3 = ~A ~2%~@
+5 reminder +3 = ~A ~@
+5 reminder -3 = ~A ~@
-5 reminder +3 = ~A ~@
-5 reminder -3 = ~A"
(mod 5 3) (mod 5 -3) (mod -5 3) (mod -5 -3)
(rem 5 3) (rem 5 -3) (rem -5 3) (rem -5 -3))
+5 modulo +3 = 2
+5 modulo -3 = -1
-5 modulo +3 = 1
-5 modulo -3 = -2
+5 reminder +3 = 2
+5 reminder -3 = 2
-5 reminder +3 = -2
-5 reminder -3 = -2
NIL
[2]>
Python uses the same definition for modulo as Common Lisp.
bye
Karl
--
"Lisp is worth learning for the profound enlightenment experience you
will have when you finally get it; that experience will make you a
better programmer for the rest of your days, even if you never
actually use Lisp itself a lot." -- Eric S. Raymond