pythonnumpyuint32

Can I force array numpy to keep its uint32 type?


I would like to reproduce C behavior in Python, presumably using numpy, but I'm running into this issue :

>>> import numpy
>>> a = numpy.uint32(4294967295)
>>> type(a)
<class 'numpy.uint32'>
>>> a += 1
>>> a
4294967296
>>> type(a)
<class 'numpy.int64'>

In C, with uint32, I'd get 4294967295 + 1 = 0

Can I force my array a to remain a numpy.uint32 array in order to get 0 at the end of my script ?

Related to this other question of mine: Does numpy exactly reproduce all C behaviors on usual operations?


Solution

  • You're not using an array here, and this matters, because NumPy doesn't necessarily have the same behavior between a scalar and an array of size one.

    For example, in-place operations on an array never change the array dtype.

    Example:

    import numpy
    a = numpy.array([4294967295], dtype='uint32')
    a += 1
    print(a)
    print(a.dtype)
    

    Output:

    [0]
    uint32
    

    Edit: NumPy 2.0 is now out, and one of the changes is that scalar type is preserved.

    >>> import numpy as np
    >>> a = np.uint32(4294967295)
    >>> a += 1
    <stdin>:1: RuntimeWarning: overflow encountered in scalar add
    >>> a
    np.uint32(0)
    >>> type(a)
    <class 'numpy.uint32'>
    

    So one alternative is to use NumPy 2.0 or higher.