Mastering E-Prime: The mod operator

David McFarlane mcfarla9 at msu.edu
Thu Mar 25 22:22:11 UTC 2010


I had some unwelcome surprises when using the mod operator provided 
in E-Basic (IOW, VBA), in particular when using negative arguments, 
and PST's E-Basic Help file does not cover this topic in enough 
detail for me (for that matter their own supplied example code will 
not compile due to undeclared variables). So I took some time to 
explore this topic in some depth, and here is the result ...

Let n and m stand for any expressions that evaluate to numeric values, and
      r = n mod m.
Then r is the "remainder" of n/m [FN1] and takes on a value in the 
interval (-m, m) (i.e., r takes the same sign as n; the sign of m is ignored).

Sometimes this is what you want, sometimes not.  If you instead want 
something that acts more like a conventional algebraic ring so that r 
remains in the interval [0, m) (i.e., r remains positive), then do 
something like the following:
     r = n mod m:  If (r < 0) Then r = r + abs(m).

Note that if n and m are Integers then mod returns an Integer, 
otherwise the values supplied by n and m are first rounded to Long 
values and then mod returns a Long.  Furthermore, Empty (i.e., 
uninitialized Variant) is treated as 0, and if either n or m are Null 
then mod returns Null.  (And if you are silly enough to use an object 
value of Nothing for either n or m then mod will produce an "Object 
variable or With block not set" runtime error, unless the other 
argument is Null, in which case mod still returns Null.  Whew!.)

Finally, for a generalized real-number "modulo" function that returns 
the remainder as defined by the division algorithm (theorem) on 
Wikipedia (e.g., fmod(7,3) = fmod(7,-3) = 1, and fmod(-7,3) = 
fmod(-7,-3) = 2), do something like the following:
     r = n - (m * fix(n/m)):  If (r < 0) Then r = r + abs(m)


[FN1]  More precisely, since the mod operator in E-Basic is strictly 
integer valued, the values supplied by n and m are first rounded to 
integer values n' and m', and then r = n' - (m' * (n\m)), where \ is 
the operator for integer division (n\m = fix(n'/m'), i.e., simple 
truncation or rounding to 0 of n/m, with n and m first rounded to 
integer values).

-- David McFarlane, Professional Faultfinder

-- 
You received this message because you are subscribed to the Google Groups "E-Prime" group.
To post to this group, send email to e-prime at googlegroups.com.
To unsubscribe from this group, send email to e-prime+unsubscribe at googlegroups.com.
For more options, visit this group at http://groups.google.com/group/e-prime?hl=en.



More information about the Eprime mailing list