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.
Unsigned integers
uint8,uint16,uint32anduint64. An -bit unsigned type holds 0 to ;uint8holds 0 to 255.Signed integers
int8toint64. An -bit signed type holds to in two’s complement, the usual encoding in which the top bit carries the weight ;int8holds to 127.Floating-point
float16,float32andfloat64: binary floating-point numbers §4.49 of the IEEE 754 standard [271].float64holds every integer of size up to exactly;float32only up to .Others:
bool, complex numbers, strings, andobject, whose elements are references to ordinary Python objects.
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:
Two arrays of the same dtype give that dtype.
uint8plusuint8isuint8, even when the sums do not fit.Two different dtypes give a type that can hold the values of both, when one exists:
uint8plusint8givesint16. No integer type holds every value of bothuint64andint64, so their sum isfloat64, which rounds integers larger than .Since NumPy 2.0, a plain Python number combined with an array takes the array’s dtype. A
uint8array plus 10 staysuint8, and auint8array plus 300 raisesOverflowError, because 300 does not fit inuint8. NumPy 1.x chose a wider type in this case, so the same line can behave differently under the two major versions.
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 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 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 plus an array of shape gives shape : 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, . The same addition in NumPy:
a = np.array([250], dtype=np.uint8)andb = np.array([10], dtype=np.uint8). The exact sum is 260, butuint8ends at 255. NumPy stores , soa + bisarray([4], dtype=uint8). This is unsigned wraparound §4.16: the bit worth 256 is lost.Widening afterwards does not help.
(a + b).astype(np.uint16)is 4, because the value 260 no longer exists anywhere.Widening before the operation does help.
a.astype(np.uint16) + badds auint16array to auint8array, so the result isuint16, which holds up to 65,535, and the result is 260.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 .The default 64-bit type overflows too.
np.array([2**62])has dtypeint64. Multiplying it by 4 gives the exact value , and NumPy stores : the result isarray([0]). In Python,2**62 * 4is 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 is accumulated in uint64. But x + x is computed element by element in uint8: each element is .
Stated precisely
Let an integer dtype have bits, and let be the exact mathematical result of an addition, subtraction or multiplication of two of its values. An array operation stores
for an unsigned dtype, , the remainder of divided by , a number from 0 to ;
for a signed dtype, the unique with such that is a multiple of .
The stored value equals exactly when lies in the range of the dtype. Otherwise the stored value differs from by a nonzero multiple of , 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 itself, limited only by memory.
For float64, each operation rounds the exact result to the nearest representable value. Every integer of size at most 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 becomes infinity, with a warning, and an invalid operation such as 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 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 .
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 from one of shape gives an array of all pairwise differences, not differences; with that is elements, which take 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 -bit integer type keeps only the low bits of each result, without an error or a warning. In Python , while two uint8 arrays holding 250 and 10 add to ; int8 127 plus 1 gives ; and even the default int64 wraps: 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].