Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork11.5k
Description
Proposed new feature or change:
When summing large integer arrays,np.sum
can silently overflow depending on the dtype and system architecture.
For example, summing anint32
array on a 32-bit system can produce incorrect results without any warning.
Reproduction
importnumpyasnparray=np.arange(10**8+1,dtype=np.int32)np.sum(array)# May overflow depending on the environment
On 64-bit systems (or when usingint64
), this gives the correct result, but on 32-bit systems or withint32
arrays, it silently wraps around due to overflow.
Proposed behavior
It would be helpful if np.sum provided one of the following features:
- Automatic dtype promotion — promote smaller integer types (e.g.
int32
→int64
) to avoid overflow, or - Optional warning parameter — e.g.
warn_on_overflow=True
, which would raise or log a warning when overflow is detected.
This would makenp.sum
more consistent with Python’s built-insum
, which automatically handles large integers, and could reduce confusion when switching between platforms.
Motivation
While this behavior is consistent with NumPy’s current design, it might be unintuitive for users who expect consistent numerical results across different architectures.
Providing a warning or an optional type promotion could make this behavior easier to understand and improve usability.