![](/img/trans.png)
[英]Is there a Numpy function for casting just one element to a different type than the rest?
[英]Numpy function type casting automatically or not
考虑以下 numpy 代码
foo = np.array([255, 255], dtype=np.uint8)
foo_sum = foo.sum()
foo_square_v1 = foo**2
foo_square_v2 = np.square(foo)
foo_square_v3 = np.pow(foo, 2)
foo_sum
正确转换为 uint64 并返回510
但是所有 3 foo_square
都没有触发类型转换并且有溢出(,!!),返回[1,1]
知道我是否应该手动进行投射,或者 numpy 是否为我自动进行投射的经验法则是什么?
我的系统:Python 3.x,X64机器,Linux,numpy 1.20.3
您似乎希望 NumPy 检测溢出并提升 dtypes 作为响应。 NumPy 永远不会那样做。 大多数 NumPy 功能将只使用与输入相同的 dtype,或者在有多个 dtype 时遵循默认的提升规则。
numpy.sum
是不寻常的,但即使它的 dtype 规则也不是你想要的。 引用numpy.sum
的文档( a是输入数组):
默认情况下使用a的 dtype,除非a的 integer dtype 的精度低于默认平台 integer。 在这种情况下,如果a已签名,则使用平台 integer,而如果a未签名,则使用与平台精度相同的未签名 integer。
这里的“默认平台整数”是 C long
(不是 C int
)。 如果 C long
是 32 位(特别是在 Windows 上)并且您需要 64 位 output 以避免溢出,您仍然需要手动指定 dtype。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.