[Numpy-discussion] scalars and strange casting

josef.pktd@gmai... josef.pktd@gmai...
Mon Dec 3 09:14:44 CST 2012


A followup on the previous thread on scalar speed.

operations with numpy scalars

I can *maybe* understand this

>>> np.array(2)[()] *  [0.5, 1]
[0.5, 1, 0.5, 1]

but don't understand this

>>> np.array(2.+0.1j)[()] * [0.5, 1]
__main__:1: ComplexWarning: Casting complex values to real discards
the imaginary part
[0.5, 1, 0.5, 1]


The difference in behavior compared to the other operators, +,-, /,**,
 looks, at least, like an inconsistency to me.


Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> np.array(2.+0.1j)[()] * [0.5, 1]
__main__:1: ComplexWarning: Casting complex values to real discards
the imaginary part
[0.5, 1, 0.5, 1]
>>> np.array(2.+0.1j)[()] ** [0.5, 1]
array([ 1.41465516+0.0353443j,  2.00000000+0.1j      ])
>>> np.array(2.+0.1j)[()] + [0.5, 1]
array([ 2.5+0.1j,  3.0+0.1j])
>>> np.array(2.+0.1j)[()] / [0.5, 1]
array([ 4.+0.2j,  2.+0.1j])


>>> np.array(2)[()] *  [0.5, 1]
[0.5, 1, 0.5, 1]
>>> np.array(2)[()] /  [0.5, 1]
array([ 4.,  2.])
>>> np.array(2)[()] **  [0.5, 1]
array([ 1.41421356,  2.        ])
>>> np.array(2)[()] -  [0.5, 1]
array([ 1.5,  1. ])
>>> np.__version__
'1.5.1'

or
>>> np.array(-2.+0.1j)[()] * [0.5, 1]
[]
>>> np.multiply(np.array(-2.+0.1j)[()], [0.5, 1])
array([-1.+0.05j, -2.+0.1j ])

>>> np.array([-2.+0.1j])[0] * [0.5, 1]
[]
>>> np.multiply(np.array([-2.+0.1j])[0], [0.5, 1])
array([-1.+0.05j, -2.+0.1j ])

Josef
defensive programming = don't use python, use numpy arrays,
or at least remember which kind of animals you have


More information about the NumPy-Discussion mailing list