首页 > 解决方案 > NumPy right_shift 给出全零

问题描述

我有

a = np.array([300, 320, 616], dtype=np.uint16)
b = np.right_shift(a, 8, dtype=np.uint8)

这导致全零b。你能解释一下这种行为吗?

标签: pythonnumpybit-shiftnumpy-ufunc

解决方案


您看到此行为的原因是因为您使用的是 uint8。将其更改为 uint16 以获得所需的结果。

https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html

基本上,在 uint8 中,数字被视为最大数字 256 的模数。所以 300 变为 300%256=44

In: np.right_shift(a, 0, dtype=np.uint8)                                   
Out: array([ 44,  64, 104], dtype=uint8)
for i in range(9): 
  print(np.right_shift(a, i, dtype=np.uint8))

will print the below 
[ 44  64 104]
[22 32 52]
[11 16 26]
[ 5  8 13]
[2 4 6]
[1 2 3]
[0 1 1]
[0 0 0]
[0 0 0]

推荐阅读