[Numpy-discussion] Integers to integer powers, let's make a decision

Peter Cock p.j.a.cock at googlemail.com
Fri Jun 10 04:11:17 EDT 2016


On Fri, Jun 10, 2016 at 7:42 AM, Nathaniel Smith <njs at pobox.com> wrote:
> On Mon, Jun 6, 2016 at 1:17 PM, Charles R Harris
> <charlesr.harris at gmail.com> wrote:
>>
>> ...
>>
>> It looks to me like users want floats, while developers want the
>> easy path of raising an error. Darn those users, they just make
>> life sooo difficult...
>
> I dunno, with my user hat on I'd be incredibly surprised / confused /
> annoyed if an innocent-looking expression like
>
>   np.arange(10) ** 2
>
> started returning floats... having exact ints is a really nice feature
> of Python/numpy as compared to R/Javascript, and while it's true that
> int64 can overflow, there are also large powers that can be more
> precisely represented as int64 than float.
>
> -n

I was about to express an preference for (1), preserving integers
on output but treating negative powers as an error. However,
I realised the use case I had in mind does not apply:

Where I've used integer matrices as network topology adjacency
matrixes, to get connectivity by paths of n steps you use A**n,
by which I mean A x A x ... A using matrix multiplication. But
in NumPy A**n will do element wise multiplication, so this
example is not helpful.

Charles R Harris <charlesr.harris at gmail.com> wrote:

>    1. Integers to negative integer powers raise an error.
>    2. Integers to integer powers always results in floats.

As an aside, using boolean matrices can be helpful in the
context of connectivity matrices. How would the proposals
here affect booleans, where there is no risk of overflow?
If we went with (2), using promotion to floats here would
be very odd:

>>> import numpy
>>> A = numpy.array([[False,True,False],[True,False,True],[True,True,False]], dtype=numpy.bool)
>>> A
array([[False,  True, False],
       [ True, False,  True],
       [ True,  True, False]], dtype=bool)
>>> A*A
array([[False,  True, False],
       [ True, False,  True],
       [ True,  True, False]], dtype=bool)
>>> A**2
array([[False,  True, False],
       [ True, False,  True],
       [ True,  True, False]], dtype=bool)
>>> numpy.dot(A,A)
array([[ True, False,  True],
       [ True,  True, False],
       [ True,  True,  True]], dtype=bool)
>>>

Regards,

Peter



More information about the NumPy-Discussion mailing list