[Numpy-discussion] Casting rules changed in trunk?

Matthew Brett matthew.brett@gmail....
Thu Mar 8 17:14:09 CST 2012


Hi,

On Wed, Mar 7, 2012 at 4:08 PM, Matthew Brett <matthew.brett@gmail.com> wrote:
> 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,

In case it wasn't clear, this, in numpy 1.6.1:

In [2]: (np.zeros((2,), dtype=np.uint8) + np.int16(257)).dtype
Out[2]: dtype('int16')

changed to this in current trunk:

In [2]: (np.zeros((2,), dtype=np.uint8) + np.int16(257)).dtype
Out[2]: dtype('uint16')

which is different still in previous versions of numpy (e.g. 1.4.1):

In [2]: (np.zeros((2,), dtype=np.uint8) + np.int16(257)).dtype
Out[2]: dtype('uint8')

My impression had been that the plan was to avoid changes in the
casting rules if possible.

Was this change in trunk intentional?  If not, I am happy to bisect,

Best,

Matthew


More information about the NumPy-Discussion mailing list