Complex Number With Python

Posted on Sun 12 November 2017 in Notebook

In [1]:
import math
import numpy as np
import pandas as pd
import scipy as sp
import sklearn
import matplotlib.pyplot as plt
import seaborn as sns

%matplotlib inline

Complex number

An example :

$$X=\left[ \begin{array}{ccc} -1-1j & 0-1j & 1-1j \\ -1+0j & 0+0j & 1+0j \\ -1+1j & 0+1j & 1+1j \end{array} \right]$$

In [2]:
MAX = 1
LENGTH = 2*MAX+1
In [3]:
x = np.arange(-MAX, MAX+1, dtype=np.int32)
y = np.arange(-MAX, MAX+1, dtype=np.int32)
X = np.array([np.complex(_x, _y) for _y in y for _x in x])
X = X.reshape(LENGTH, LENGTH)
In [4]:
X
Out[4]:
array([[-1.-1.j,  0.-1.j,  1.-1.j],
       [-1.+0.j,  0.+0.j,  1.+0.j],
       [-1.+1.j,  0.+1.j,  1.+1.j]])

Real Part

In [5]:
X.real
Out[5]:
array([[-1.,  0.,  1.],
       [-1.,  0.,  1.],
       [-1.,  0.,  1.]])

Imaginary Part

In [6]:
X.imag
Out[6]:
array([[-1., -1., -1.],
       [ 0.,  0.,  0.],
       [ 1.,  1.,  1.]])

Absolute value

Sited from "Complex number - Wikipedia"

In [7]:
r = np.absolute(X)
r
Out[7]:
array([[ 1.41421356,  1.        ,  1.41421356],
       [ 1.        ,  0.        ,  1.        ],
       [ 1.41421356,  1.        ,  1.41421356]])
In [8]:
im = plt.imshow(r, extent=[-1, 1, -1, 1])
plt.colorbar(im)
Out[8]:
<matplotlib.colorbar.Colorbar at 0x1099c42d0>

Angle

$$\arg \left( j \right)=\frac{\pi }{2}$$

In [9]:
np.pi / 2.0
Out[9]:
1.5707963267948966
In [10]:
phi = np.angle(X)
phi
Out[10]:
array([[-2.35619449, -1.57079633, -0.78539816],
       [ 3.14159265,  0.        ,  0.        ],
       [ 2.35619449,  1.57079633,  0.78539816]])
In [11]:
im = plt.imshow(phi, extent=[-1, 1, -1, 1])
plt.colorbar(im)
Out[11]:
<matplotlib.colorbar.Colorbar at 0x109eb4590>

Range more widely

In [12]:
x = np.arange(-5, 5+1,0.1)
y = np.arange(-5, 5+1, 0.1)
In [13]:
Y = np.array([np.complex(_x, _y) for _y in y for _x in x])
In [14]:
l = int(math.sqrt(Y.shape[0]))
In [15]:
Y = Y.reshape(l, l)
In [16]:
im = plt.imshow(np.angle(Y), extent=[-5,5,-5,5])
plt.colorbar(im)
Out[16]:
<matplotlib.colorbar.Colorbar at 0x10a057ed0>
In [17]:
im = plt.imshow(np.absolute(Y), extent=[-5,5,-5,5])
plt.colorbar(im)
Out[17]:
<matplotlib.colorbar.Colorbar at 0x10a2d0890>