Integer division

Matthew P. Wiener weemba at brahms.BERKELEY.EDU
Thu Jan 30 11:28:58 AEST 1986


In article <332 at ism780c.UUCP> tim at ism780c.UUCP (Tim Smith) writes:
>[Which is preferred: (-a)%b == - (a%b) or (-a)%b >= 0 always?]
>Are there any good mathematical grounds for choosing one alternative over
>the other here?  Note that I am not asking from a hardware point of view
>which is better.  I want to know mathematically if one is better than
>the other.

I have NEVER seen an instance where the first one is preferable.  Not
only is it not preferable, it is just incorrect.  Why such a routine
has been allowed to be 50% inaccurate in every existing language all
these years is beyond me.

But since that is what you get, I have always had to program around it,
sometimes thinking of clever ways to prevent negative numbers from being
fed into the remaindering.

Even in non-mathematical usages, the second is preferred.  For example,
if you have a circular list of length N, kept in an array, i=change(i)%N
is the usual way most steps through the list are done, for some integer
function change(i).

At one research institute I have worked at, IMOD is put in the Fortran
library, to be used instead of MOD, so as to get the correct remainder.
MOD was left for portability from other people's software, not for usage.

[I pity the fool who says "but the first is faster".]

[Whether CS people should even be *allowed* to make such mathematical
decisions is another question.  In C on UNIX, for example, one has
log(-x) == log(x), a rather dangerous identity, not based on anything
comprehensible.  Thus, the implementation of general exponentiation,
a**b = pow(a,b) = exp( b*log(a) ) will silently return the wrong value
if a is negative.  (Try taking cube roots this way!)]

ucbvax!brahms!weemba	Matthew P Wiener/UCB Math Dept/Berkeley CA 94720



More information about the Comp.lang.c mailing list