且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

numpy.sum()在大型数组上给出奇怪的结果

更新时间:2023-01-28 16:22:22

这显然是numpy的整数类型,溢出了32位.通常,您可以使用np.seterr将numpy配置为在这种情况下失败:

This is clearly numpy's integer type overflowing 32-bits. Normally you can configure numpy to fail in such situations using np.seterr:

>>> import numpy as np
>>> np.seterr(over='raise')
{'divide': 'warn', 'invalid': 'warn', 'over': 'warn', 'under': 'ignore'}
>>> np.int8(127) + np.int8(2)
FloatingPointError: overflow encountered in byte_scalars

但是,sum被明确记录为行为"在溢出时不会引发错误",因此您在这里可能不走运.为了方便起见,使用numpy通常是性能的折衷!

However, sum is explicitly documented with the behaviour "No error is raised on overflow", so you might be out of luck here. Using numpy is often a trade-off of performance for convenience!

但是,您可以手动指定累加器的dtype,如下所示:

You can however manually specify the dtype for the accumulator, like this:

>>> a = np.ones(129)
>>> a.sum(dtype=np.int8)  # will overflow
-127
>>> a.sum(dtype=np.int64)  # no overflow
129

观看票证#593 ,因为这是一个未解决的问题,可能是由numpy devs修复.

Watch ticket #593, because this is an open issue and it might be fixed by numpy devs sometime.