[Numpy-discussion] numpy oddity
Olivier Delalleau
shish@keba...
Tue Aug 30 10:01:53 CDT 2011
2011/8/30 Charles R Harris <charlesr.harris@gmail.com>
>
>
> On Tue, Aug 30, 2011 at 8:33 AM, Johann Cohen-Tanugi <
> johann.cohentanugi@gmail.com> wrote:
>
>> I have numpy version 1.6.1 and I see the following behavior :
>>
>> In [380]: X
>> Out[380]: 1.0476157527896641
>>
>> In [381]: X.__class__
>> Out[381]: numpy.float64
>>
>> In [382]: (2,3)*X
>> Out[382]: (2, 3)
>>
>> In [383]: (2,3)/X
>> Out[383]: array([ 1.90909691, 2.86364537])
>>
>> In [384]: X=float(X)
>>
>> In [385]: (2,3)/X
>>
>> ---------------------------------------------------------------------------
>> TypeError Traceback (most recent call
>> last)
>> /home/cohen/<ipython-input-385-cafbe080bfd5> in <module>()
>> ----> 1 (2,3)/X
>>
>> TypeError: unsupported operand type(s) for /: 'tuple' and 'float'
>>
>>
>> So it appears that X being a numpy float allows numpy to play some trick
>> on the tuple so that division becomes possible, which regular built-in
>> float does not allow arithmetics with tuples.
>> But why is multiplication with "*" not following the same prescription?
>>
>>
> That's strange.
>
> In [16]: x = float64(2.1)
>
> In [17]: (2,3)*x
> Out[17]: (2, 3, 2, 3)
>
> In [18]: (2,3)/x
> Out[18]: array([ 0.95238095, 1.42857143])
>
> Note that in the first case x is treated like an integer. In the second the
> tuple is turned into an array. I think both of these cases should raise
> exceptions.
>
> Chuck
>
>
>
The tuple does not know what to do with /, so Python asks the numpy float if
it can do something when dividing a tuple, and numpy implements this (see
http://docs.python.org/reference/datamodel.html?highlight=radd#object.__radd__for
how reflected operands work).
That part makes sense to me. The behavior with * doesn't though, it
definitely seems wrong.
-=- Olivier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20110830/f0492d6e/attachment.html
More information about the NumPy-Discussion
mailing list