numpy bug?

Ben Caradoc-Davies bmcd at es.co.nz
Fri Jun 16 22:05:03 EDT 2000


On 16 Jun 2000 21:05:11 -0400, Warren B. Focke <moron at Glue.umd.edu> wrote:
>
>Huaiyu Zhu sez:
>[Numeric and Python integer division don't agree.]
>
>	Numeric just calls the C operators for / and %.  C leaves the
>rounding direction for integer division up to the implementor if both
>operands are not positive, but does require that (a/b)*b + a%b == a as
>long as b != 0.  So NumPy gets it right from that point of view.

The problem is that NumPy shouldn't be consistent with your C implementation
but with Python!

>	Python does specify the rounding direction, in a manner that
>has been extensively argured in this group to be correct.  I don't
>really remember the reasons at the moment, check dejanews, it's on
>there somewhere, I'm sure.

I don't recall the discussion, but the Python choice has one clear weakness:
         (-5)/4 != -(5/4)
For the new C standard (C 1999) (as opposed to the implementation dependence of
C 1989), rounding is towards zero i.e. drop any fraction part. Then:
         (-5)/4 == -(5/4)
which is more consistent with algebra.

However, I prefer the Python choice because is it invariant under a
translation, that is, you always know your rounding direction if you know the
sign of your denominator (negative for positive denominator), even if you don't
know the sign of your numerator. This also gives the lovely property that your
remainder has the same sign as your denominator (or is zero). The C99 choice
doesn't have this.

If anyone still isn't convinced that Python's way is the right way, plot, or
even just look at:

print (arange(21)-10)/2

It has  kink in it! By comparison

for i in range(21): print (i-10)/2,

has two of each value in a smooth succession. Plot it (against i), and the line
is straight.

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



More information about the Python-list mailing list