Numpy: Integers to negative integer powers are not allowed

Created on 9 Apr 2017  路  8Comments  路  Source: numpy/numpy

Components:
Numpy-1.12.0
Python-3.5.3
Description:
10**-5 is fine,
But do it in a for loop ValueError raise.
Here is the code

>>> [10**c for c in np.arange(-5,5)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
ValueError: Integers to negative integer powers are not allowed.
>>> 10**0
1
>>> 10**-1
0.1
>>> 10**-2
0.01
>>> 10**-3
0.001
>>> 10**-4
0.0001
>>> 10**-5
1e-05
>>> 10**1
10
>>> 10**2
100
>>> 10**3
1000
>>> 10**4
10000
>>> 10**5
100000
53 - Invalid

Most helpful comment

A quick fix for anyone dropping by: create the exponent as float.

[10**c for c in np.arange(-5,5, dtype=float)]

All 8 comments

A lot of numpy functions don't do implicit type coercions.

For scalars this may seem weird but for arrays it makes sense, because np.power should know what the result dtype is just by looking at the dtype of the operands.

What you're seeing here is the difference between 10 ** np.int32(-1) and 10 ** -1. np.arange does not return python ints, but returns numpy scalars.

np.int32(10) ** np.int32(-1) raises this exception by design. There is perhaps an argument that when one of the arguments is a python scalar, the result should always be a float

(@eric-wieser means np.int_(1) in case you try it and are confused. np.int is a silly alias for Python's built in int.)

Oops, good catch. Can we do #6103 already?

This behavior seems stupid.

A quick fix for anyone dropping by: create the exponent as float.

[10**c for c in np.arange(-5,5, dtype=float)]

I just use range() function.

[10**c for c in np.arange(-5,5, dtype=float)]

or just:
10**np.arange(-5,5, dtype=float)

Was this page helpful?
0 / 5 - 0 ratings