Are casts and overflows well-defined for numpy signed integer types?

Viewed 199

On my machine, I can observe the following behavior for numpy’s integer data types:

>>> import numpy
>>> numpy.uint8(-1)
255
>>> numpy.int8(128)
-128
>>> numpy.int8(-129)
127
>>> numpy.int8(127) + numpy.int8(1)
# RuntimeWarning: overflow encountered in byte_scalars
-128
>>> numpy.int8(-128) - numpy.int8(1)
# RuntimeWarning: overflow encountered in byte_scalars
127

So in all cases, when creating a value of a given type, the input overflows or underflows by wrapping around to the other end of the range of representable values (without a warning), as for unsigned integers. When an overflow or underflow occurs during an operation like addition, the behavior is the same, but a RuntimeWarning is emitted.

Now, my question is whether this behavior can be relied on, or whether it can vary depending on the underlying C compiler, since signed integer overflow is undefined behavior in C. The only relevant part of numpy’s documentation which I could find is this section on overflow errors, which does give an example involving a signed integer type, but does not explicitly specify what the rules are for casts and overflows and whether the behavior can be expected to be the same across all platforms.

0 Answers
Related