My problem is that
np.array([2**31], dtype=np.uint32) >> 32
does not return 0
, but returns array([2147483648], dtype=uint32)
instead. The same is true for
np.right_shift(np.array([2**31], dtype=np.uint32), 32)
(so I believe this is simply how >>
is implemented).
Interestingly, all these alternatives seem to work as expected, returning some kind of 0
:
print(
2**31 >> 32,
np.uint32(2**31) >> 32,
np.array(2**31, dtype=np.uint32) >> 32,
np.right_shift(2**31, 32),
np.right_shift([2**31], 32),
np.right_shift(np.uint32(2**31), 32),
np.right_shift(np.array(2**31, dtype=np.uint32), 32),
)
In particular, what is different between Numpy arrays representing 2147483648
and [2147483648]
?
I have seen this issue in JavaScript (Why does << 32 not result in 0 in javascript?) and C++ (Weird behavior of right shift operator (1 >> 32), Why is `int >> 32` not always zero?), but not yet in Python/Numpy. In fact, neither Python nor Numpy docs seem to be documenting this behavior:
>> 31
returns you 1 and<< 16
returns you 0 which are expected results. Maybe by doing>> 32
it changes its type into a double or a thing like thatnp.array([123], dtype=np.uint32) >> 32
equalsnp.array([123], dtype=np.uint32)
And even more(np.array([123], dtype=np.uint32) >> 33)
equals(np.array([123], dtype=np.uint32) >> 1)
Really not expected.