[Numpy-discussion] Casting rules changed in trunk?

Matthew Brett matthew.brett at gmail.com
Wed Mar 7 19:08:39 EST 2012


Hi,

I noticed a casting change running the test suite on our image reader,
nibabel: https://github.com/nipy/nibabel/blob/master/nibabel/tests/test_casting.py

For this script:

<pre>
import numpy as np

Adata = np.zeros((2,), dtype=np.uint8)
Bdata = np.zeros((2,), dtype=np.int16)
Bzero = np.int16(0)
Bbig = np.int16(256)

print np.__version__
print 'Array add', (Adata + Bdata).dtype
print 'Scalar 0 add', (Adata + Bzero).dtype
print 'Scalar 256 add', (Adata + Bbig).dtype
</pre>

1.4.1
Array add int16
Scalar 0 add uint8
Scalar 256 add uint8

1.5.1
Array add int16
Scalar 0 add uint8
Scalar 256 add uint8

1.6.1
Array add int16
Scalar 0 add uint8
Scalar 256 add int16

1.7.0.dev-aae5b0a
Array add int16
Scalar 0 add uint8
Scalar 256 add uint16

I can understand the uint8 outputs from numpy < 1.6 - the rule being
not to upcast for scalars.

I can understand the int16 output from 1.6.1 on the basis that the
value is outside uint8 range and therefore we might prefer a type that
can handle values from both uint8 and int16.

Was the current change intended?  It has the following odd effect:

In [5]: Adata + np.int16(257)
Out[5]: array([257, 257], dtype=uint16)

In [7]: Adata + np.int16(-257)
Out[7]: array([-257, -257], dtype=int16)

In [8]: Adata - np.int16(257)
Out[8]: array([65279, 65279], dtype=uint16)

but I guess you can argue that there are odd effects for other choices too,

Best,

Matthew



More information about the NumPy-Discussion mailing list