numpy bug?

Ben Caradoc-Davies bmcd at es.co.nz
Fri Jun 16 21:31:38 EDT 2000


On Sat, 17 Jun 2000 00:18:34 GMT, Huaiyu Zhu <hzhu at knowledgetrack.com> wrote:
>>>> from Numeric import *
>>>> a = arange(16)
>>>> (a-5)/4
>array([-1, -1,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  2,  2,  2])

Numerical Python is rounding towards zero.

>I believe this is not correct. 

I agree, this behaviour is inconsistent with "stock" Python. In general, the
choice of rounding direction varies between languages or implementations, but
fortunately Python fixes this. See below.

> And the stock python gives correct result:
>
>>>> for i in a: print -i/4
>... 
>0
>-1
>-1
>-1
>-1
>-2
>-2
>-2
>-2
>-3
>-3
>-3
>-3
>-4
>-4
>-4
>
>Any enlightenments?

"Stock" Python is rounding towards negative infinity, as required by the
language definiton (see "Binary arithmetic operations").

The C (1989) standard sidesteps this issue and doesn't specify a direction of
rounding, and merely states that the identity (a/b)*b+a%b==a holds. If either a
or b is negative, not even the signs of the divisor or remainder are specified.
This vagueness is (I assume) to support the various hardware implementations.

The new C (1999) standard (or at least the C9X draft I have) requires rounding
towards zero, fixing the vagueness of the above standard [or at least breaking
it consistently :-)   ].

GNU C rounds towards zero (on all platforms).

It seems that Numerical Python has left the rounding direction to the
underlying C implementation. As a C programmer, I'm used to not relying on the
rounding direction, but need not be inflicted on Numerical Python programmers.

This should be fixed.

-- 
Ben Caradoc-Davies <bmcd at es.co.nz>



More information about the Python-list mailing list