Sub topic 13
Data types and overflow in aggregations
This chapter assumes you can create arrays with np.array and np.arange, read .shape and .dtype, and use axis with sum, mean, max, and cumsum. It covers what data type NumPy uses for an aggregation result and how to avoid silent wrong answers. Overflow in NumPy produces wrong numbers without an error.
Why the dtype matters
Every NumPy array has a data type (dtype) that fixes how many bits each element uses. An int8 holds values from -128 to 127. A uint8 holds 0 to 255. An int64 holds roughly ±9.2 × 10^18. When a result does not fit its type, NumPy wraps around instead of raising an error.
An aggregation adds many elements together, so its total can be far larger than any single element. NumPy therefore chooses the accumulator type (the type used for the running total) separately from the input type.
Default result types
| Function | Input dtype | Result dtype |
|---|---|---|
| `sum`, `cumsum`, `prod` | `bool`, `int8` to `int32`, `uint8` to `uint32` | platform integer (`int64`) or its unsigned version (`uint64`) |
| `sum`, `cumsum`, `prod` | `int64`, `uint64` | unchanged, so overflow is possible |
| `sum`, `cumsum` | `float32`, `float64` | unchanged |
| `mean` | any integer or `bool` | `float64` |
| `mean` | `float32` | `float32`, with a `float32` accumulator |
| `max`, `min` | any | unchanged |
| `argmax`, `argmin` | any | integer index type (`intp`) |
The "platform integer" is 64-bit on current Linux and macOS, and on Windows with NumPy 2. On Windows with NumPy 1.x it is 32-bit, so the same code can overflow on one machine and not on another. Check .dtype rather than assuming.
Small integer types are widened for you
A uint8 array holds image brightness values. Summing 200 and 100 in 8 bits would give 44, but NumPy widens the accumulator first.
import numpy as np
a = np.array([[200, 100],
[100, 100]], dtype=np.uint8)
print(a.dtype) # uint8
print(a.sum(axis=0)) # [300 200]
print(a.sum(axis=0).dtype) # uint64
print(a.max(axis=0).dtype) # uint8
print(a.mean(axis=0)) # [150. 100.]sum widens to uint64, so 300 is correct. max can never exceed the largest input, so it keeps uint8. mean returns float64 for integer input, so the division is exact.
64-bit integers still overflow
Widening stops at 64 bits. Past that, the total wraps to a negative number, and NumPy does not warn for array operations.
import numpy as np
big = np.array([[2**62, 1],
[2**62, 1]], dtype=np.int64)
print(big.sum(axis=0)) # [-9223372036854775808 2]
print(big.sum(axis=1)) # [4611686018427387905 4611686018427387905]The column total 2^63 does not fit in int64, so it wraps to -2^63. The row totals fit and are correct. The same array gives both a right and a wrong answer depending on axis. Overflow depends on which elements are added together.
One fix is to switch to floating point, which trades exactness for range:
import numpy as np
big = np.array([[2**62, 1],
[2**62, 1]], dtype=np.int64)
print(big.sum(axis=0, dtype=np.float64)) # [9.22337204e+18 2.00000000e+00]float64 represents 2^63 correctly but keeps only about 15 to 16 significant digits. Large integer totals can lose their low digits. If you need exact integers beyond 64 bits, use Python integers with dtype=object. It is much slower.
Choosing the accumulator with `dtype=`
Aggregations accept a dtype argument that sets the accumulator and result type. It does not change the input array.
import numpy as np
a = np.array([[100, 100],
[100, 100]], dtype=np.int8)
print(a.sum(axis=0)) # [200 200]
print(a.sum(axis=0, dtype=np.int8)) # [-56 -56]
print(a.sum(axis=0, dtype=np.int8).dtype) # int8The default result is correct because int8 input is widened. Forcing dtype=np.int8 shows the failure: 200 does not fit in 8 bits and wraps to -56. You usually want the opposite, a wider type than the default. For example, dtype=np.float64 for float32 data, as shown below.
Precision loss in floating point
Floats do not overflow in the same way. They lose precision, and the loss grows when small numbers are added to large running totals. A float32 has about 7 significant decimal digits.
import numpy as np
x = np.array([16777216.0, 1.0], dtype=np.float32)
print(x.sum()) # 16777216.0
print(x.sum(dtype=np.float64)) # 16777217.016,777,216 is 2^24. Above that value, float32 cannot represent every integer, so adding 1 changes nothing. Using dtype=np.float64 for the accumulator fixes it without converting the whole array first, which would copy the data.
NumPy sums along a contiguous axis with pairwise summation, which reduces rounding error compared with a plain left-to-right loop. This helps but does not remove the limit. The accumulator type still sets the precision. The same applies to mean on float32 arrays, so pass dtype=np.float64 when the data is large or the values differ greatly in size.
Booleans and counting
A boolean array sums as integers, with True counting as 1. This is a common way to count matches along an axis, and the result is already a wide integer.
import numpy as np
scores = np.array([[55, 80, 91],
[72, 40, 68]])
passed = scores >= 60
print(passed.sum(axis=0)) # [0 1 2] is wrong; see the output belowWork through that last line by hand before reading on. Column 0 has 55 and 72, so one value is at least 60. Column 1 has 80 and 40, so one. Column 2 has 91 and 68, so two. The correct output is [1 1 2], and the comment above is wrong on purpose to show that you should predict results and then check them. Run the corrected code:
import numpy as np
scores = np.array([[55, 80, 91],
[72, 40, 68]])
passed = scores >= 60
print(passed.sum(axis=0)) # [1 1 2]
print(passed.sum(axis=0).dtype) # int64 on most platforms
print(passed.mean(axis=1)) # [0.66666667 0.66666667]mean on a boolean array gives the fraction of True values, as float64.
Cumulative functions follow the same rules
cumsum uses the same accumulator rule as sum. A uint8 input produces a uint64 output, but an int64 input can still wrap. Because cumsum keeps the input shape, an overflow part-way along the axis makes every later entry in that line wrong, not just one.
import numpy as np
a = np.array([[200, 100, 100]], dtype=np.uint8)
print(np.cumsum(a, axis=1)) # [[200 300 400]]
print(np.cumsum(a, axis=1, dtype=np.uint8)) # [[200 44 144]]A decision procedure
Checking before you aggregate
You can estimate the worst case without running the sum. The largest possible total along an axis is the largest absolute element times the number of elements added.
import numpy as np
def safe_for_int64(arr, axis):
n = arr.shape[axis]
worst = int(np.abs(arr).max()) * n # Python int, cannot overflow
return worst <= np.iinfo(np.int64).max
data = np.array([[2**62, 1],
[2**62, 1]], dtype=np.int64)
print(safe_for_int64(data, axis=0)) # False
print(safe_for_int64(data, axis=1)) # TrueConverting to a Python int before the multiplication is what keeps the check itself from overflowing. np.abs of the most negative int64 value overflows too, which is an edge case this check does not cover. The bound is conservative: it can say "unsafe" when the real total would fit.
Common mistakes
- Assuming
dtype=np.int8on the input means the sum is computed in 8 bits. The default widens, so overflow appears only if you force a narrowdtypeor reach 64 bits. - Reading a correct answer on one machine as proof the code is portable. A 32-bit platform integer on older Windows builds changes the result.
- Casting a large array with
astype(np.float64)just to sum it. Thedtype=argument avoids the copy. - Forgetting that
maxandminkeep the input dtype, so assigning their result into a narrower array later can truncate values. - Testing overflow on a small array and not on the full data. Totals grow with the number of elements along the axis.
Exercise
An array a = np.full((1000, 3), 200, dtype=np.uint8) is summed with a.sum(axis=0). What are the result values and dtype, and what happens if you call a.sum(axis=0, dtype=np.uint8) instead?
Show answer
The default sum widens the accumulator to uint64, so the result is [200000 200000 200000] (1000 × 200 for each column). With dtype=np.uint8 the accumulator has only 8 bits, so each total wraps modulo 256. 200000 mod 256 is 64, so the result is [64 64 64].
Exercise
You have a float32 array x with 50 million readings and call x.mean(axis=0). Name one risk and show the call that reduces it without copying the array.
Show answer
A float32 accumulator keeps only about 7 significant digits, so the mean can lose precision when many values of different sizes are added. Call x.mean(axis=0, dtype=np.float64), which accumulates in float64 and does not create a converted copy of x.