マンデルブロ集合は、複素数平面上の点の集合であり、特定の条件を満たす点が属している集合です。Pythonを使用して、マンデルブロ集合を描画することができます。
必要なライブラリ
numpymatplotlib
マンデルブロ集合の定義
マンデルブロ集合は以下の条件を満たす複素数 $c$ からなる集合です。
$$ \forall c \in \mathbb{C} ; \exists ; \text{n} \in \mathbb{N} : |z_n(c)| > 2 $$
ここで、$z_0(c) = 0$ であり、$z_{n+1}(c) = z_n^2(c) + c$ と定義されます。
マンデルブロ集合を描画する方法
Pythonを使ってマンデルブロ集合を描画するには、複素平面上に点をプロットし、上記の条件を満たすかどうかを判断します。具体的には、複素数 $c$ を複素平面上の点 $(x, y)$ として表現し、それを初期値として $z_n$ を計算します。$|z_n|$ が $2$ を超えた場合は、その点 $(x, y)$ をマンデルブロ集合に属する点として判定します。
以下のコードは、$[-2, 2]$ の範囲で $1000 \times 1000$ のグリッドを作成し、それぞれの点がマンデルブロ集合に属するかどうかを判定し、結果を画像として出力する例です。
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot(c, max_iter):
z = c
for i in range(max_iter):
if abs(z) > 2:
return i
z = z**2 + c
return max_iter
def plot_mandelbrot(xmin, xmax, ymin, ymax, nx, ny, max_iter):
x, y = np.meshgrid(np.linspace(xmin, xmax, nx), np.linspace(ymin, ymax, ny))
c = x + y*1j
mandelbrot_set = np.frompyfunc(lambda c: mandelbrot(c, max_iter), 1, 1)(c).astype(np.float)
plt.imshow(mandelbrot_set, extent=(xmin, xmax, ymin, ymax), cmap='hot')
plt.axis('off')
plt.show()
plot_mandelbrot(-2, 2, -2, 2, 1000, 1000, 100)
このコードを実行すると、マンデルブロ集合の画像が表示されます。