Section 12.29

NumPy

Full name: Numerical Python (NumPy).

Definition

NumPy is the standard library for numerical computing in Python §12.23. Its central object, the n-dimensional array §14.5 (type ndarray), holds many numbers of one element type, called the dtype (data type), stored as raw machine values in one block of memory. NumPy applies an operation to every element in compiled code, many times faster than a Python loop. Each dtype has a fixed width, such as 8 or 64 bits. Array arithmetic therefore follows machine rules: unlike a Python integer, which grows to any size, an array element can overflow.

The idea

A Python list of integers is a list of separate objects. Each element carries its own type information, and a loop over the list runs one interpreted step per element. NumPy stores the same numbers as raw machine values, side by side, and runs the loop in compiled code, so whole-array operations such as a sum or an element-by-element product run many times faster. It also gives a compact notation: a + b adds two arrays element by element without a written loop.

The speed has a price. A Python integer has no upper limit: 2**64 is simply 18446744073709551616. A NumPy element is a machine number of fixed width, so the rules of machine arithmetic come back. A result that does not fit wraps around, a conversion to a narrower type drops high bits, and a floating-point value is rounded. A car odometer with three digits is a fair picture: at 999, one more kilometer shows 000. The picture stops in two ways. A dtype wraps at a power of two, not a power of ten. And a signed dtype wraps from its largest positive value to its most negative value.

How it works

Element types. The main dtypes are these.

Creating arrays. np.array([250, 10], dtype=np.uint8) creates an array with a chosen dtype; np is the usual short name for the module numpy. Without dtype, NumPy picks a type from the data. Python integers become the default integer type, which is int64 on 64-bit Linux and macOS and, since NumPy 2.0, on 64-bit Windows as well. Python floating-point numbers become float64.

Operations and the result type. An arithmetic operator, or a function such as np.add, works element by element; NumPy calls such a function a universal function, or ufunc. The dtype of the result follows NumPy’s promotion rules:

Integer overflow inside an array operation is silent: no exception and no warning. An operation on single NumPy scalars, such as np.uint8(250) + np.uint8(10), prints a RuntimeWarning but still returns the wrapped value.

Reductions. A reduction combines many elements into one, as sum does, or into running results, as cumsum does. For an integer array narrower than the default integer type, sum and cumsum accumulate in a 64-bit integer (signed for signed input, unsigned for unsigned input) on 64-bit systems. The accumulator is still finite: an int64 sum that exceeds 263−12^{63} - 1 wraps silently. mean accumulates integers in float64. The dtype argument of a reduction chooses the accumulator explicitly.

Conversions. astype converts an array to another dtype. A conversion to a narrower integer type, a narrowing conversion §4.19, keeps only the low bits: 300 becomes 300−256=44300 - 256 = 44 in uint8. A conversion from floating-point to integer drops the fractional part, and a floating-point value outside the target range gives a meaningless integer. Neither conversion raises an exception.

Shapes. An array has a shape, the length along each dimension. Broadcasting combines arrays of different shapes by stretching every dimension of length 1 to match the other array. An array of shape (3,1)(3, 1) plus an array of shape (4,)(4,) gives shape (3,4)(3, 4): all 12 pairwise sums.

Random numbers. rng = np.random.default_rng(12345) creates a generator object from the seed 12345, and calls such as rng.random(5) draw numbers from it. NumPy promises the same numbers only for the same seed, the same sequence of calls with the same arguments, the same build of NumPy and the same machine. Its policy allows a feature release to change the numbers a method produces, and five calls of rng.random() need not give the same numbers as one call of rng.random(5). Record the NumPy version and the seed with any result. The older functions such as np.random.rand share one hidden global generator.

Worked example

In Python, 250+10=260250 + 10 = 260. The same addition in NumPy:

  1. a = np.array([250], dtype=np.uint8) and b = np.array([10], dtype=np.uint8). The exact sum is 260, but uint8 ends at 255. NumPy stores 260mod256=260−256=4260 \bmod 256 = 260 - 256 = 4, so a + b is array([4], dtype=uint8). This is unsigned wraparound §4.16: the bit worth 256 is lost.

  2. Widening afterwards does not help. (a + b).astype(np.uint16) is 4, because the value 260 no longer exists anywhere.

  3. Widening before the operation does help. a.astype(np.uint16) + b adds a uint16 array to a uint8 array, so the result is uint16, which holds up to 65,535, and the result is 260.

  4. A signed type wraps to negative values. np.array([127], dtype=np.int8) + np.array([1], dtype=np.int8): the exact sum 128 exceeds 127, and NumPy stores 128−256=−128128 - 256 = -128.

  5. The default 64-bit type overflows too. np.array([2**62]) has dtype int64. Multiplying it by 4 gives the exact value 264=18,446,744,073,709,551,6162^{64} = 18{,}446{,}744{,}073{,}709{,}551{,}616, and NumPy stores 264−264=02^{64} - 2^{64} = 0: the result is array([0]). In Python, 2**62 * 4 is 18446744073709551616.

Reductions and element-wise operations differ. Take x = np.full(100, 250, dtype=np.uint8), 100 elements of value 250. x.sum() returns 25000, because 100×250=25,000100 \times 250 = 25{,}000 is accumulated in uint64. But x + x is computed element by element in uint8: each element is 500−256=244500 - 256 = 244.

Stated precisely

Let an integer dtype have NN bits, and let rr be the exact mathematical result of an addition, subtraction or multiplication of two of its values. An array operation stores

The stored value equals rr exactly when rr lies in the range of the dtype. Otherwise the stored value differs from rr by a nonzero multiple of 2N2^N, and array operations report nothing. The NumPy user guide on data types shows this behavior and contrasts it with Python’s integer type, which always returns rr itself, limited only by memory.

For float64, each operation rounds the exact result to the nearest representable value. Every integer of size at most 2532^{53} is representable, so integer arithmetic in float64 is exact while all inputs, intermediate results and outputs stay within that size. A result larger than about 1.8×103081.8 \times 10^{308} becomes infinity, with a warning, and an invalid operation such as 0/00 / 0 gives a NaN (not a number). The binary floating-point entry explains rounding and these special values.

The rule for exact integer work follows: before each operation, choose a dtype whose range contains every value that the operation can produce, not only the inputs and the final result.

Limits and common mistakes

Widening after the fact cannot restore lost bits. The only fix is to convert to a wider type before the operation that can overflow.

A 64-bit default does not remove overflow; it only moves the limit to about 9.2×10189.2 \times 10^{18} for int64. Products of large counts, nanosecond timestamps multiplied by a factor, and powers reach it quickly. For integers that may exceed 64 bits, use Python integers, or an object array, which stores Python integers and is exact but slow.

Mixing uint64 and int64 turns integers into float64 and silently rounds values above 2532^{53}.

Promotion rules changed between NumPy 1.x and 2.x. Code that relied on a Python number widening an array’s type behaves differently after an upgrade; state dtypes explicitly.

Broadcasting can produce a large array by accident. Subtracting an array of shape (n,)(n,) from one of shape (n,1)(n, 1) gives an n×nn \times n array of all pairwise differences, not nn differences; with n=100,000n = 100{,}000 that is 101010^{10} elements, which take 8×10108 \times 10^{10} bytes, 80 gigabytes, as float64.

Speed is not correctness. Moving a calculation from a Python loop into NumPy changes its number types, so check its results against the loop on small inputs, including values at the edges of each dtype’s range.

Questions answered

Can fixed-width array arithmetic overflow even when Python integers do not?

Yes. A Python integer grows to whatever size the result needs, but each element of a NumPy array has a fixed width set by its dtype (data type), and NumPy (Numerical Python) array arithmetic on an NN-bit integer type keeps only the low NN bits of each result, without an error or a warning. In Python 250+10=260250 + 10 = 260, while two uint8 arrays holding 250 and 10 add to 260−256=4260 - 256 = 4; int8 127 plus 1 gives −128-128; and even the default int64 wraps: 262×42^{62} \times 4 gives 0.

Converting the result to a wider type afterwards still gives the wrong value, because the high bits are already gone. To get exact results, choose a dtype wide enough for every intermediate value and convert the operands before the operation (a.astype(np.uint16) + b gives 260), choose the accumulator of a reduction explicitly with its dtype argument, and use Python integers when values can exceed 64 bits.

Related entries: Unsigned modular arithmetic (§4.16), Estimand and estimator (§11.2), Python (§12.23), Truncation and extension (§4.19), Binary floating-point representation, special values, and rounding (§4.49), Signed integer overflow (§4.15). Further reading: [28, 115, 271].