(Numeric) should -7 % 5 = -2 ?

Tim Roberts timr at probo.com
Tue Jul 1 06:35:41 CEST 2003

"Louis M. Pecora" <pecora at anvil.nrl.navy.mil> wrote:

>Fredrik Lundh <fredrik at pythonware.com> wrote:
>> > >>> -7 % 5
>> > 3
>> > >>> Numeric.array(-7) % 5
>> > -2
>> > >>> Numeric.remainder(-7, 5)
>> > -2
>> looks like Numeric implements C semantics, which is different
>> from how Python does it.
>Hmmm...  "remainder" makes sense.  But "%" is mod, right.  IIRC from my
>abstract algebra days (only 30 yrs ago :-) ) The "X mod n" function
>maps onto the postive integers from 0 to n-1.  So sounds like numeric
>contradicts the math texts.  Not good since it's a math module.

That's a bit harsh.  The problem is that there is no universal agreement in
the world of computer science as to what the semantics of the modulo
operator should be when presented with a negative operand.  Contradicting
Fredrik, something I do with great reluctance, the C standard specifies
that the behavior is implementation-defined, so in fact BOTH answers
"implement C semantics".

Fortran, on the other hand, defines A mod P as A-INT(A/P)*P, which is
exactly what Numeric produces.  Since folks interested in numerical
programming often have a strong Fortran background, it is not terribly
surprising that Numeric should follow Fortran's lead.
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.

More information about the Python-list mailing list