Naively benefitting from symmetry#

We’ve seen that the Mandelbrot Set is symmetrical around the x-Axis.

Can we save some computation time because of this?

Sure thing!

  • Use functools.cache to decorate our core function to benefit from previously calculated results.

  • Use abs() on the imaginary component to make the previously actually happen.

Hide 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
from functools import cache

def mandelbrot_set(x_min, x_max, y_min, y_max, max_iterations, resolution):
    
    # mind the cache
    @cache
    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:
            # notice the use of abs()
            row.append(mandel(_x, abs(_y), max_iterations))

        iterations.append(row)
    
    return iterations
Hide code cell source
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 2.6 seconds.
Hide 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()

Noticed a problem here?

Hide code cell content
mandel.cache_info()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 mandel.cache_info()

NameError: name 'mandel' is not defined