[Numpy-discussion] wrong casting of augmented assignment statements

josef.pktd at gmail.com josef.pktd at gmail.com
Tue Jan 12 13:11:29 EST 2010


On Tue, Jan 12, 2010 at 1:05 PM, Sebastian Walter
<sebastian.walter at gmail.com> wrote:
> Hello,
> I have a question about the augmented assignment statements *=, +=, etc.
> Apparently, the casting of types is not working correctly. Is this
> known resp. intended behavior of numpy?
> (I'm using numpy.__version__ = '1.4.0.dev7039' on this machine but I
> remember a recent checkout of numpy yielded the same result).
>
> The problem is best explained at some examples:
>
> wrong casting from float to int::
>
>            In [1]: import numpy
>
>            In [2]: x = numpy.ones(2,dtype=int)
>
>            In [3]: y = 1.3 * numpy.ones(2,dtype=float)
>
>            In [4]: z = x * y
>
>            In [5]: z
>            Out[5]: array([ 1.3,  1.3])
>
>            In [6]: x *= y
>
>            In [7]: x
>            Out[7]: array([1, 1])
>
>            In [8]: x.dtype
>            Out[8]: dtype('int32')
>
>  wrong casting from float to object::
>
>            In [1]: import numpy
>
>            In [2]: import adolc
>
>            In [3]: x = adolc.adouble(numpy.array([1,2,3],dtype=float))
>
>            In [4]: y = numpy.array([4,5,6],dtype=float)
>
>            In [5]: x
>            Out[5]: array([1(a), 2(a), 3(a)], dtype=object)
>
>            In [6]: y
>            Out[6]: array([ 4.,  5.,  6.])
>
>            In [7]: x * y
>            Out[7]: array([4(a), 10(a), 18(a)], dtype=object)
>
>            In [8]: y *= x
>
>            In [9]: y
>
>            Out[9]: array([ 4.,  5.,  6.])
>
>
>        It is inconsistent to the Python behavior::
>
>            In [9]: a = 1
>
>            In [10]: b = 1.3
>
>            In [11]: c = a * b
>
>            In [12]: c
>            Out[12]: 1.3
>
>            In [13]: a *= b
>
>            In [14]: a
>            Out[14]: 1.3
>
>
> I would expect that numpy should at least raise an exception in the
> case of casting object to float.
> Any thoughts?

You are assigning to an existing array, which implies casting to the
dtype of that array. It's the behavior that I would expect. If you
want upcasting then don't use inplace *= , ...

Josef


>
> regards,
> Sebastian
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>



More information about the NumPy-Discussion mailing list