From the following code:
import numpy as np
print 2**np.array([32, 33])
I get the negative numbers [-2147483648 -2147483648]
. I'm using python 2.6. Is it some sort of bug? On the contrary print 2**32
gives the correct answer 4294967296
.
From the following code:
import numpy as np
print 2**np.array([32, 33])
I get the negative numbers [-2147483648 -2147483648]
. I'm using python 2.6. Is it some sort of bug? On the contrary print 2**32
gives the correct answer 4294967296
.
These values are too big to store in a 32-bit int
which numpy
uses by default. If you set the datatype to float
(or 64-bit int
) you get the proper results:
import numpy as np
print 2 ** np.array([32, 33], dtype=np.float)
# [ 4.2946730e+09 8.58993459e+09 ]
print 2 ** np.array([32, 33], dtype=np.int64) # 64-bit int as suggested by PM 2Ring
# [ 4294967296 8589934592]
It is because when using numpy the numbers given will have a certain size, for example a 32 or 64 bit int. These will overflow in the given calculations, and give negative numbers.
Try making them floats, it should help:
print 2**np.array([32., 33.])