Front page | perl.perl5.porters | Postings from October 2001

## Re: Bug with modulo operator and negative operands

From:
John Peacock
Date:
October 24, 2001 09:56
Subject:
Re: Bug with modulo operator and negative operands
Message ID:
3BD6F2EB.A193C818@rowman.com
Mike Guy wrote:
>
> > -11 % 2 = 1
> > -11 % 2 = -1
>
> which is exactly as it's defined to behave.
>
> > Regardless of the validity of the argument that the modulo should
> > be -1 in this case, the 'use integer;' should have no effect on
> > the answer on any single machine.
>
> What "argument that the modulo should be -1" ?    The mathematically
> correct value is 1.    "use integer" is defined to give the same
> result as the underlying C, which on most platforms does not give
> mathematically correct results.

OK, I did a little more research and yes, the mathematically correct
answer is 1, since the definition I found is

The mod function is defined as the amount by which a number
exceeds the largest integer multiple of the divisor that is
not greater than that number.

However, in this discussion here:

http://mathforum.org/dr.math/problems/anne.4.28.99.html

it is suggested that the % operator in most computer C libraries is
more appropriately labled the "remainder" operator, which will be
identical to mod() for positive operands and different for negative.
In fact, the description in Camel for the % operator states that "[%]
converts its operands to integers before finding the REMAINDER
according to integer division" (emphasis mine).

It is the inconsistency which is a bug, not the returned value, IMHO.
If the underlying c-library treats the % operator as a remainder
operator (on all platforms I can find), why does Perl need to be

Would it be more appropriate to expose a new function div() which
simply implements the underlying C-function (after appropriate integer
conversion) that returns quotient and remainder of integer division?
This is really what we need for Math::BigInt calculations to produce
sensible results.

John

--
John Peacock
Director of Information Research and Technology
Rowman & Littlefield Publishing Group
4720 Boston Way
Lanham, MD 20706
301-459-3366 x.5010
fax 301-429-5747