32

What is the equivalent of Octave's j in NumPy? How can I use j in Python?

In Octave:

octave:1> j
ans =  0 + 1i
octave:1> j*pi/4
ans =  0.00000 + 0.78540i

But in Python:

>>> import numpy as np
>>> np.imag
<function imag at 0x2368140>
>>> np.imag(3)
array(0)
>>> np.imag(3,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: imag() takes exactly 1 argument (2 given)
>>> np.imag(32)
array(0)
>>> 
>>> 0+np.imag(1)
1

3 Answers 3

57

In Python, 1j or 0+1j is a literal of complex type. You can broadcast that into an array using expressions, for example

In [17]: 1j * np.arange(5)
Out[17]: array([ 0.+0.j,  0.+1.j,  0.+2.j,  0.+3.j,  0.+4.j])

Create an array from literals:

In [18]: np.array([1j])
Out[18]: array([ 0.+1.j])

Note that what Michael9 posted creates a complex, not a complex array:

In [21]: np.complex(0,1)
Out[21]: 1j
In [22]: type(_)
Out[22]: complex
0
10

You can create one if needed or use 1j which instance of complex class

 >>> 1j #complex object
 1j
 >>> type(1j)
 <class 'complex'>
 >>> j = np.complex(0,1) #create complex number
 >>> j
 1j
0

You must use Python built-in 1j in order to distinguish this constant from variable j:

from numpy import pi, arange, exp, imag, real
from matplotlib import pyplot as plt

# Some sine wave parameters and sampling times
A = 1; f = 1; af = 2*pi*f; p0 = pi/2
Ts = 5e-3
tn = arange(-1, 1, Ts)

# Build complex array, plot real and imag parts
zn = A * exp(1j * (af*tn + p0))
plt.plot(tn, real(zn), tn, imag(zn))
plt.legend(('real', 'imag'))

zn array content:

array([
-1.83697020e-16+1.00000000e+00j,
-3.14107591e-02+9.99506560e-01j,
-6.27905195e-02+9.98026728e-01j, ...

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.