[Numpy-discussion] Casting and promotion rules (e.g. int + uint64 => float)
Sergio Callegari
sergio.callegari at gmail.com
Fri Mar 8 11:23:33 EST 2013
Hi,
I have noticed that numpy introduces some unexpected type casts, that are
in some cases problematic.
A very weird cast is
int + uint64 -> float
for instance, consider the following snippet:
import numpy as np
a=np.uint64(1)
a+1
-> 2.0
this cast is quite different from what other programming languages (e.g., C)
would do in this case, so it already comes unexpected.
Furthermore, an int64 (or an uint64) is too large to fit into a float,
hence this automatic conversion also results in data loss! For instance
consider:
a=np.uint64(18446744073709551614)
a+np.uint64(1)
-> 18446744073709551615 # CORRECT!
a+1
-> 1.8446744073709552e+19
# Actually 1.84467440737095516160e+19 - LOSS OF DATA
in fact
np.uint64(a+1)
-> 0
Weird, isn't it?
Another issue is that variables unexpectedly change type with accumulation
operators
a=np.uint64(1)
a+=1
now a is float
I believe that some casting/promotion rules should be revised, since they
now lead to difficult to catch, intermittent errors. In case this cannot
be done immediately, I suggest at least documenting these promotions,
providing examples on how to code many conventional tasks. E.g.,
incrementing an integer of unknown size
b=a+type(a)(1)
I have also reported this in https://github.com/numpy/numpy/issues/3118
Thanks!
More information about the NumPy-Discussion
mailing list