Can I force array numpy to keep its uint32 type?

74 Views Asked by At

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?

1

There are 1 best solutions below

0
Nick ODell On BEST ANSWER

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