Floren
Floren

Reputation: 55

Python 3.6.1 - Numpy.power returns negative values for cube powers of positive int numbers

If I ask Python for the cube power of 1963 I get:

In[1]: 1963**3
Out[1]: 7564163347

But if I define an array and ask numpy.power to return the cube powers I get:

In[1]: a=nu.array([1, 3, 5, 1963])
In[2]: nu.power(a)
Out[2]: array([1, 27, 125, -1025771245], dtype=int32)

Why is it returning some numbers correctly but not others? Do I need to mark all the numbers as float in the original array? Why does it have a problem with the array but not when I directly ask for the cube power (e.g. 1961**3)?

I noticed that this works:

In[1]: a=nu.array([1, 3, 5, 1963.0])
In[2]: nu.power(a)
Out[2]: array([1.00000000e+00, 2.70000000e+01, 1.25000000e+02, 7.56416335e+09])

Thanks!

Upvotes: 3

Views: 1353

Answers (1)

Charlie Allatson
Charlie Allatson

Reputation: 76

This happens because the cube of 1963 is greater than the maximum number (2,147,483,647) which can be stored in a 32 bit integer.

You need to tell numpy to use 64 bit integers for this operation which you can do by specifying the dtype parameter like this:

a = nu.array([1, 3, 5, 1963], dtype="int64")

or using the long python type like this:

a = nu.array([1, 3, 5, 1963L])

Both give the correct output:

>>> nu.power(a, 3) array([1, 27, 125, 7564163347], dtype=int64)

EDIT: The reason this doesn't happen when doing:

1963**3

is because Python automatically converts the output to the long type.

EDIT2: Apologies, Python 3 doesn't have a separate long type, only the first example works in Python 3, both are valid Python 2.

Upvotes: 3

Related Questions