You may access the real and imaginary parts of a complex number using the real and imag attributes. Those attributes are read-only; in other words, they cannot be changed:
z = 1j
z.real # 0.0
z.imag # 1.0
z.imag = 2 # AttributeError: readonly attribute
It is not possible to convert a complex number to a real number:
z = 1 + 0j
z == 1 # True
float(z) # TypeError
Interestingly, the real and imag attributes as well as the conjugate method work just as well for complex arrays; see also Section 4.3.1, Array properties. We demonstrate this by computing the Nth roots of unity, which are , that is, the solutions of the equation :
from matplotlib.pyplot import *
N = 10
# the following vector contains the Nth roots of unity:
unity_roots = array([exp(1j*2*pi*k/N) for k in range(N)])
# access all the real or imaginary parts with real or imag:
axes(aspect='equal')
plot(unity_roots.real, unity_roots.imag, 'o')
allclose(unity_roots**N, 1) # True
The resulting figure shows the 10 roots of unity. In Figure 2.2, it is completed by a title and axes labels and shown together with the unit circle. (For more details on how to make plots, see Chapter 6: Plotting.)
It is, of course, possible to mix the previous methods, as illustrated by the following examples:
z = 3.2+5.2j
(z + z.conjugate()) / 2. # returns (3.2+0j)
((z + z.conjugate()) / 2.).real # returns 3.2
(z - z.conjugate()) / 2. # returns 5.2j
((z - z.conjugate()) / 2.).imag # returns 5.2
sqrt(z * z.conjugate()) # returns (6.1057350089894991+0j)