Re: Modulus and negative operands





August Karlstrom wrote On 01/12/06 14:01,:
> Michael Mair wrote:
>
>>% is defined in terms of / (see below).
>>If / rounds down, then % yields positive values.
>>If / rounds to zero, you get the observed behaviour.
>
> [snip]
>
> OK, but what's the benefit of this behavior?

The benefit of "truncate toward zero" on division are
mostly conventional: That's the way practically all known
hardware does division, and that's also the way Fortran
defines it. According to the C99 Rationale, compatibility
with Fortran was the main reason for requiring "truncate
toward zero."

Quotient and remainder are governed by the identity

(a / b) * b + (a % b) == a

(unless the division itself is undefined). Whichever
way the quotient is chosen on an inexact division, the
modulus must "balance" the truncation error. If division
truncates toward zero, the truncated negative quotient
will be larger than the true mathematical quotient, so
the "correction" must be negative.

> If I want to decrement a
> cyclic variable n by k I have to write something like
>
> n = ((n - k) % length + length) % length

If k <= length, this can be simplified to

n = (n - k + length) % length

or to

if ((n -= k) < 0)
n += length;

--
Eric.Sosman@xxxxxxx



.



Relevant Pages

  • Re: efficiency question
    ... So all you need is to seek to zero and ... |> truncate before closing to ensure that nothing is written to disk. ... Josuttis actually has an example sample stream buffer ...
    (alt.comp.lang.learn.c-cpp)
  • [PATCH 1/2] eCryptfs: fix write zeros behavior
    ... This patch fixes the processes involved in wiping regions of the data ... during truncate and write events, fixing a kernel hang in 2.6.22-rc4 ... while assuring that zero values are written out to the appropriate ...
    (Linux-Kernel)
  • Re: Negative Modulus
    ... MOD and REM are generalizations of the modulus and remainder ... MOD & REM are defined in terms of the FLOOR & TRUNCATE functions: ... FLOOR and FFLOOR produce a quotient that has been truncated ... mathematical quotient. ...
    (sci.crypt)
  • Re: [OT] Rounding v Truncation, was: Re: Platform Support vs.
    ... actually maybe take a poll. ... One would expect different results in different BASIC dialects. ... previous poster is right VB rounds, ... the INTfunction is _defined_ to truncate. ...
    (comp.os.vms)
  • Re: [Lit.] Buffer overruns
    ... > was allowed to truncate toward zero or toward minus ... > infinity, and there was the same invariant ... > toward zero. ...
    (sci.crypt)