3

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.)

2
  • I think you'll find that there isn't one. Commented Aug 15, 2012 at 6:54
  • @IgnacioVazquez-Abrams I added a comment to the question, that I just want to avoid the full check of possible dtypes. For example, a + b works just fine, but assigning a part of the array does not. Commented Aug 15, 2012 at 6:59

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That is ok, but what if b is real, and I do not want to convert to complex in this case?
@IvanOseledets in that case check with np.iscomplexobj(b).
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.