_trac用户tlatorre在2011-08-10发行的原始票证http://projects.scipy.org/numpy/ticket/1931 ,已分配给未知帐户。
>>> np.uint64(5) << 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ufunc 'left_shift' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule 'safe'
>>> np.uint64(5) >> 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ufunc 'right_shift' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule 'safe'
_ @ charris写于2011-08-13_
这是因为移位编号将转换为有符号类型,并且没有足够大的有符号整数类型容纳uint64。 移位运算符需要特殊情况,它们也可能在Intel上失败,因为硬件会屏蔽掉不需要的位,即,对于int32,仅查看低5位。
_trac用户parejkoj发表于2012-07-27_
我可以使用以下lambda对此进行编码:
lshift = lambda x,s: np.uint64(x)*np.uint64(2**s)
这可行,但不是理想的。 将其修复为numpy将非常有用。
五年后...这不是一个重要的问题吗? 无符号整数应该对移位没有歧义。
更简单的解决方法是对移位使用无符号整数:
np.uint64(5) << np.uint64(1)
正如上面提到的
更简单的解决方法是对移位使用无符号整数:
np.uint64(5)<< np.uint64(1)
...如果知道您正在对numpy整数进行运算,那么它确实可以工作,但是如果您使用的是通用代码(尤其是已经在另一个模块中写入但不受您控制的东西),例如
def f(x):
return x | (x >> 1)
那么您将无法同时在常规Python整数和np.uint64类型上使用它。
我并不是要说这是微不足道的(比我的技能高一些),但我确实认为应该将其作为优先事项。
@ jason-s-我同意这个问题非常烦人...可悲的是,我们当中没有多少人充分了解ufunc在内部的工作方式...
但是,也许可以至少有特殊情况的标量来改变方法,而不是依靠常规的ufunc机制。 @charris :这是您要记住的(如果您可以记住6年后的情况;-)。
另请参阅#8002。
就个人而言,如果我们能再做一遍,我将倾向于重做所有的强制转换/强制转换,以便numpy强制转换本质上类似于C强制转换,并遵循C-casting的精神处理C中不存在的情况。规则有点怪异,有时会造成混淆(例如,将uint64 + int64
为float64
)。 但是我们在列表上讨论了很多,似乎很难改变。
当遇到这种情况时(请参阅我的评论),我只是将每个值都包装在np.uint64
。
最有用的评论
更简单的解决方法是对移位使用无符号整数:
正如上面提到的