import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
a = complex(2, 3)
print(a)
b = 1+2j
print(b)
a+b
a-b
a*b
a/b
roots = np.array([complex(np.cos(2*np.pi*i/3), np.sin(2*np.pi*i/3)) for i in range(3)])
print(roots)
x = np.arange(4)
y = np.arange(3)
print(x)
print(y)
X, Y = np.meshgrid(x, y)
print(X)
print(Y)
First create 1d arrays of the real and imaginary values used for the grid.
npts = 5
x = np.linspace(-1, 1, npts)
y = np.linspace(-1j, 1j, npts)
print(x, y)
X, Y = np.meshgrid(x, y)
print(X)
print(Y)
Z = X+Y
print(Z)
import warnings
warnings.filterwarnings('ignore')
niters = 15
for i in range(niters):
Z = Z - (Z**3 - 1)/(3*Z**2)
print(Z)
tol = 0.01
root1 = np.abs(Z - roots[0]) < tol
print(root1)
root2 = np.abs(Z - roots[1]) < tol
root3 = np.abs(Z - roots[2]) < tol
img = np.zeros((npts, npts, 3))
img[:,:,0] = root1
img[:,:,1] = root2
img[:,:,2] = root3
plt.imshow(img);
We can use an array of booleans as an index for another array. The only elements selected are those with a matching True in the index array.
a = np.arange(5)
print(a)
b = np.array([True, True, False, False, True])
print(b)
print(a[b])
a = np.arange(5)
print(a)
print(a > 2)
print(a[a > 2])
b = (a % 2 == 0)
print(b)
a[b] = 100
print(a)
img = np.zeros((npts, npts, 3))
img[root1] = [1, 1, 0]
img[root2] = [0, 1, 1]
img[root3] = [1, 0, 1]
plt.imshow(img);