Wrapping all calculations into a function#
We will have a look at several implementations to calculate views of the Mandelbrot Set
.
To support this some sort of api is helpful, abstracting the base calling convention and defining the necessary bits.
It looks like this.
Show code cell content
%matplotlib widget
import time
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 300
x_min, x_max = -2.5, 1.0
y_min, y_max = -1.25, 1.25
max_iterations = 100
resolution = 1000
def mandelbrot_set(x_min, x_max, y_min, y_max, max_iterations, resolution):
def mandel(x, y, max_iterations):
c = complex(x, y)
c0 = c
for iteration in range(max_iterations):
c = c**2 + c0
if abs(c) > 2.0:
break
return iteration
x = [x_min + (x_max - x_min) / (resolution - 1) * index for index in range(resolution)]
y = [y_min + (y_max - y_min) / (resolution - 1) * index for index in range(resolution)]
iterations = []
for _y in y:
row = []
for _x in x:
row.append(mandel(_x, _y, max_iterations))
iterations.append(row)
return iterations
tic = time.perf_counter()
iterations = mandelbrot_set(x_min, x_max, y_min, y_max, max_iterations, resolution)
toc = time.perf_counter()
print(f"Calculating the mandelbrot set took {toc-tic:.1f} seconds.")
Calculating the mandelbrot set took 3.2 seconds.
Show code cell content
fig, axes = plt.subplots()
axes.imshow(iterations[::-1], extent=(x_min, x_max, y_min, y_max), cmap="RdGy")
plt.tight_layout()