Re: Modulus and negative operands
- From: Eric Sosman <eric.sosman@xxxxxxx>
- Date: Thu, 12 Jan 2006 14:56:57 -0500
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
.
- References:
- Modulus and negative operands
- From: August Karlstrom
- Re: Modulus and negative operands
- From: Michael Mair
- Re: Modulus and negative operands
- From: August Karlstrom
- Modulus and negative operands
- Prev by Date: Re: Why We Use C Than C++...
- Next by Date: Re: Why We Use C Than C++...
- Previous by thread: Re: Modulus and negative operands
- Index(es):
Relevant Pages
|