[Numpy-discussion] *= operator not intuitive

Paul Anton Letnes paul.anton.letnes at gmail.com
Wed Mar 16 10:59:45 EDT 2011


On 16. mars 2011, at 15.57, Dag Sverre Seljebotn wrote:

> On 03/16/2011 02:35 PM, Paul Anton Letnes wrote:
>> Heisann!
> 
> Hei der,
> 
>> On 16. mars 2011, at 14.30, Dag Sverre Seljebotn wrote:
>> 
>>> On 03/16/2011 02:24 PM, Paul Anton Letnes wrote:
>>>> Hi!
>>>> 
>>>> This little snippet of code tricked me (in a more convoluted form). The *= operator does not change the datatype of the left hand side array. Is this intentional? It did fool me and throw my results quite a bit off. I always assumed that 'a *= b' means exactly the same as 'a = a * b' but this is clearly not the case!
>>> 
>>> In [1]: a = np.ones(5)
>> Here, a is numpy.float64:
>>>>> numpy.ones(5).dtype
>> dtype('float64')
>> 
>>> In [2]: b = a
>>> 
>>> In [3]: c = a * 2
>>> 
>>> In [4]: b
>>> Out[4]: array([ 1.,  1.,  1.,  1.,  1.])
>>> 
>>> In [5]: a *= 2
>> So since a is already float, and b is the same object as a, the resulting a and b are of course floats.
>>> In [6]: b
>>> Out[6]: array([ 2.,  2.,  2.,  2.,  2.])
>>> 
>> This is not the case I am describing, as in my case, a was of dtype integer.
>> Or did I miss something?
> 
> I was just trying to demonstrate that it is NOT the case that "a = a * 2 
> is exactly the same as a *= 2". If you assume that the two statements 
> are the same, then it does not make sense that b = [1, 1, ...] the first 
> time around, but b = [2, 2, 2...] the second time around. And in trying 
> to figure out why that happened, perhaps you'd see how it all fits 
> together...
> 
> OK, it perhaps wasn't a very good explanation...
> 
> Dag Sverre

I see, I misunderstood your point. That's another interesting aspect of this, though.

Paul.




More information about the NumPy-Discussion mailing list