[Numpy-discussion] Behaviour of integer powers

Robert Kern robert.kern at gmail.com
Sun Feb 8 05:09:23 EST 2009


On Sun, Feb 8, 2009 at 03:54, Stéfan van der Walt <stefan at sun.ac.za> wrote:
> Hi all,
>
> Ticket #955 (http://scipy.org/scipy/numpy/ticket/955) touches on the
> following issue:
>
>>>> 0.0 ** np.array([-1, 0, 1], dtype=np.int32)
> array([ Inf,   1.,   0.])
>>>> 0.0 ** np.array([-1, 0, 1], dtype=np.int32)[0]
> ------------------------------------------------------------
> Traceback (most recent call last):
>  File "<ipython console>", line 1, in <module>
> ZeroDivisionError: 0.0 cannot be raised to a negative power
>
> This is on a 32-bit platform.
>
> As I understand this happens because, in the second case, Python sees
> that "-1" is an int and does the power operation.  In other words,
> when we raise to the power of an array, the NumPy machinery is
> involved, whereas if we raise to np.int32(-1), it is not.  This is due
> to the int32 type deriving from the Python int.
>
> I can't think of an easy way to address the problem, but I was hoping
> to get some advice from the list.

I don't think there is anything we can do to fix this except not to
subclass from int. I think float.__pow__(self, other) checks that
isinstance(other, int) and does its own thing. numpy.int_.__rpow__
will never get called, and that's the only place we can implement our
logic.

We can document the wart and recommend casting the base to a float64
scalar first.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list