Search code examples
pythonnumpypython-cmath

Generating Numpy Arrays of Complex Numbers


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]

Solution

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