MOD function does not work! So be warned!

Dar Scott dsc at swcp.com
Sat Apr 6 15:13:02 EST 2002


On Friday, April 5, 2002, at 05:24 PM, Dar Scott wrote:

> The definition from Knuth's _Fundamental Algorithms_ is this:
>
> x mod y = x - y * floor( x/y ) if y is not 0
> x mod 0 = x
> where x and y are real numbers

I can't believe I'm contributing to the beating on mod.

Actually, there are two real areas of concern with mod that have 
nothing to do with approximate representation of floating point 
numbers.  These are not cause for changing the function, but areas 
where good understanding and documentation can help.

1. mod vs rem
Many people make a distinction between the modulus function and the 
remainder function:
x rem y = x - y * trunc( x/y )

Where modulus uses floor(), remainder uses trunc().

In language references you will sometimes find where mod is 
described a comment like this: "...(actually the remainder 
function)...".  In other references for languages that have both 
functions you will find phrases like "... in contrast to the rem 
function...".

The Revolution mod function is actually remainder (based on the 
above definitions).

Revolution is in good company.  I think Tcl and ANSI C define mod 
and fmod respectively as remainder functions.

The difference between modulus and remainder shows up when 
arguments are negative.  This can be a surprise in some 
applications of mod.  Suppose you have a card that is treated as a 
cylinder and you use mod to adjust the x position of a control to 
keep it on the card; falling off the left does not move the control 
to the right as one might expect.

(Perhaps the best way to show that mod is remainder in 
documentation is to include some negative numbers in examples.)

2. x mod 0
What should this do?

Knuth and traditional C say return x.  I think Knuth did this so 
that x mod y = 0 means "x is a multiple of y."

Many languages say error.  Error is an option in ANSI C (or was in '89).

Some languages say return 0.  Zero is an option in ANSI C ('89).  
An argument can be made for this.

What does Revolution do?  Error.  If y can get small or you need 
isMultipleOf(), check for y=0.

(A single line in doc examples can get this across.  The caveat 
currently in the 1.1.1 Transcript Dictionary is good, too.)

3. Mathematical modulus
(An extra wisecrack)

Though the mathematical function modulus is related to modulo 
arithmetic, it has taken on a life on its own.  Because of it this 
it might be debatable as to whether it only applies to integers (or 
even positive numbers) in general.

(Nevertheless, a warning relating to the representation limitations 
of large numbers or numbers with fractional parts is appropriate, 
especially in relation to functions like mod and trunc() that have 
discontinuities.)

Dar Scott






More information about the use-livecode mailing list