Ivan Oseledets
Ivan Oseledets

Reputation: 2290

Numpy arrays, fancy indexing, complex numbers

The following code multiplies a part of the array by a number

def mul_by_num(a,b):
    a[0:2] *= b


import numpy as np
a = np.ones(5,dtype=np.float64)
mul_by_num(a,1.0)
mul_by_num(a,1j) #Generates a warning (and casts to float!)

The second call generates a warning

-c:2: ComplexWarning: Casting complex values to real discards the imaginary part

The question is, what is the most pythonic way to multiply parts of numpy arrays by complex/real numbers without messing with dtypes? I do not really want to convert an array to complex from the beginning, but the program in principle can get a complex input.

EDIT:

I do not care about copying the full array, casting it to complex; But I want to avoid checking dtypes (i.e., np.float32, np.float64, np.complex, np.int etc.)

Upvotes: 3

Views: 11894

Answers (2)

ecatmur
ecatmur

Reputation: 157354

You're going to need to convert the array to complex at some point, otherwise it won't be able to hold complex numbers.

The easiest way to convert an array to complex is to add 0j:

if (np.iscomplexobj(b)):
    a = a + 0j
a[0:2] *= b

note: not a += 0j as that will attempt to modify the array inplace, which won't work if it isn't complex already.

Upvotes: 5

conjohn668
conjohn668

Reputation: 23

Since increasing the speed of calculating, numpy array makes sure that having same type. May be you can try the python list or casting it.

Upvotes: 0

Related Questions