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]
Matt
  • 190
  • 2
  • 12
  • `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. – hpaulj Mar 31 '22 at 02:51

1 Answers1

1

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

yut23
  • 2,624
  • 10
  • 18
  • Or, as one line, just `E0 * np.exp( 1j * (k * z - w * t) )` – Daniel F Mar 31 '22 at 08:20
  • Thanks, this is exactly what I was after. Couldn't find a use like this in the documentation, or in random searching online. – Matt Apr 15 '22 at 22:48