[英]Numpy function type casting automatically or not
consider the following numpy code考虑以下 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
get correctly casted to uint64 and return 510
But all the 3 foo_square
trigger no type casting and have an overflow (,!!), returning [1,1]
foo_sum
正确转换为 uint64 并返回510
但是所有 3 foo_square
都没有触发类型转换并且有溢出(,!!),返回[1,1]
What's the rule of thumb to know whether I should do casting manually, or whether numpy do it automatically for me?知道我是否应该手动进行投射,或者 numpy 是否为我自动进行投射的经验法则是什么?
My system: Python 3.x, X64 machine, Linux, numpy 1.20.3我的系统:Python 3.x,X64机器,Linux,numpy 1.20.3
You seem to want NumPy to detect overflow and promote dtypes in response.您似乎希望 NumPy 检测溢出并提升 dtypes 作为响应。 NumPy will never do that.
NumPy 永远不会那样做。 Most NumPy functionality will just use the same dtype as the input, or follow the default promotion rules when there are multiple dtypes.
大多数 NumPy 功能将只使用与输入相同的 dtype,或者在有多个 dtype 时遵循默认的提升规则。
numpy.sum
is unusual, but even its dtype rules aren't what you want. numpy.sum
是不寻常的,但即使它的 dtype 规则也不是你想要的。 Quoting thedocs for numpy.sum
( a is the input array):引用
numpy.sum
的文档( a是输入数组):
The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer.
默认情况下使用a的 dtype,除非a的 integer dtype 的精度低于默认平台 integer。 In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.
在这种情况下,如果a已签名,则使用平台 integer,而如果a未签名,则使用与平台精度相同的未签名 integer。
The "default platform integer" here is C long
(not C int
).这里的“默认平台整数”是 C
long
(不是 C int
)。 If C long
is 32-bit (particularly on Windows) and you need a 64-bit output to avoid overflow, you'll still need to specify the dtype manually.如果 C
long
是 32 位(特别是在 Windows 上)并且您需要 64 位 output 以避免溢出,您仍然需要手动指定 dtype。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.