Integer division

Gene Ward Smith gsmith at brahms.BERKELEY.EDU
Wed Feb 12 22:15:42 AEST 1986


In article <1133 at mmintl.UUCP> franka at mmintl.UUCP (Frank Adams) writes:

>We seem to agree that there are three at least somewhat important identities.
>
>1) (a/b)*b + a%b = a
>2) (a+b)%b = a%b        or  (a+b)/b = a/b + 1
>3) (-a)%b = -(a%b)      or  (-a)/b = -(a/b)
>
>Now, in fact, (3) in the division form is important.  The area I know of
>where it is important is in financial applications.  Suppose I own 200
>shares of stock, which I purchased at a total cost of $2,098.75, including
>commission.  I now sell 100 shares.  I have to compute the cost basis for
>those 100 shares: $1,049.38.  Now, suppose I had a short position with the
>same cost basis: -$2,098.75.  If I buy back half of these, the rounding
>has to be done the same way: -$1,049.38.
>

>Of course, this application is not rounding toward zero; it is rounding
>to the *nearest* penny.  So what we want for this application is to round
>to the nearest integer, with 1/2 rounded away from zero.  This choice is
>very common in financial applications.  (By the way, financial applications
>fairly often divide by negative numbers.)
>
>There are also a lot of number theoretic algorithms which run faster if
>the least absolute remainder is used; I once heard a professor of
>mathematics (Hans Zassenhaus, if memory serves) state that the least
>absolute remainder is what computer division *should* return.
>

  The ususal definition in elementary number theory texts, etc. is
that the remainder be positive. For many purposes, it does not matter
what the range of the remainder function is *AS LONG AS IT IS CONSISTENT*.
The way "%" has of flipping around to a negative range for negative 
numbers is the incredibly inconsistent and annoying feature I object
to. As far as nearest integer vs. positive goes, some times one wants
one, sometimes the other, and ususally either will do as long as things
are kept consistent.

>I believe that computers (CISC) and programming languages should provide
>at least three different division and remainder operations: round towards
>0, round towards -infinity, and round to nearest (with 1/2 rounded away
>from 0).  There is something to be said for round away from zero, and
>round to +infinity, as well.

 I have no objection, but *always* there should be one non-screwed-up
definition.

ucbvax!brahms!gsmith    Gene Ward Smith/UCB Math Dept/Berkeley CA 94720
ucbvax!weyl!gsmith      "When Ubizmo talks, people listen."



More information about the Comp.lang.c mailing list