0

How can I quickly generate a numpy array of calculated complex numbers? By which I mean, the imaginary component is calculated from an array of values.

I have tried using python's literal j without luck. It seems to only accept float and int cases. cmath refuses to handle arrays. Below is my current attempt.

import numpy as np
import cmath

E0, k, z, w = np.ones(4)

def Ex(t):
    exp = complex(0,k*z-w*t)
    return E0*np.exp(exp)

t = np.arange(0,10,0.01)
E = Ex(t)

this nets the following error:

~\AppData\Local\Temp/ipykernel_8444/3633149291.py in Ex(t)
      7 
      8 def Ex(t):
----> 9     exp = complex(0,k*z-w*t)
     10     return E0*np.exp(exp)
     11 

TypeError: only size-1 arrays can be converted to Python scalars

I am also open to solutions which do not utilize cmath but I had no luck forming arrays of complex numbers without the following workaround:

times = np.arange(0,10,0.01)
E = [Ex(t) for t in times]
1
  • complex(1,3) is a python function that takes 2 numbers and returns one complex one. It isn't designed to take numpy arrays (or lists). But 1j can be used in computations, multiplying and adding. Commented Mar 31, 2022 at 2:51

1 Answer 1

1

The standard way to do this is exp = 1j*(k*z-w*t).

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

2 Comments

Or, as one line, just E0 * np.exp( 1j * (k * z - w * t) )
Thanks, this is exactly what I was after. Couldn't find a use like this in the documentation, or in random searching online.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.