Visualizing the Sierpinski Carpet in Python
Fractals are fascinating mathematical objects that have captivated the attention of scientists, mathematicians, and artists alike. One of the most famous fractals is the Sierpinski Carpet, which is a self-similar pattern made up of smaller and smaller copies of itself. This fractal is created by recursively removing the middle third of each side of a square, and then repeating this process with each of the remaining smaller squares. In this article, we will explore how to visualize the Sierpinski Carpet in Python using the matplotlib library. We will also create an animation that demonstrates the step-by-step construction of the fractal. So let’s dive in and explore the beauty of the Sierpinski Carpet!
As you can guess from the description in the introduction, the code to create the carpet uses recursion. At every level, we call the same function to get the carpet one level below. Here is the code that gives us the carpet for a given depth/level represented as a numpy array filled with ones for white and zeros for black:
import numpy as np
import matplotlib.pyplot as plt
def sierpinski_carpet(depth):
if depth == 0:
return np.ones((1, 1))
carpet = sierpinski_carpet(depth - 1)
center = np.zeros_like(carpet)
squares = np.block([[carpet, carpet, carpet],
[carpet, center, carpet],
[carpet, carpet, carpet]])
return squares
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_aspect('equal')
ax.set_axis_off()
carpet = sierpinski_carpet(depth=5)
plt.imshow(carpet, cmap='binary')
plt.show()
Now let’s add an animation so that we can see the construction of the carpet step by step. We’ll use matplotlib’s FuncAnimation feature for that:
from matplotlib.animation import FuncAnimation
%matplotlib notebook
# Set up the initial plot
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_aspect('equal')
ax.set_axis_off()
carpet = sierpinski_carpet(depth=1)
im = ax.imshow(carpet, cmap='binary')
# Define the update function for the animation
def update(depth):
carpet = sierpinski_carpet(depth)
im.set_data(carpet)
return [im]
# Create the animation object and display it
ani = FuncAnimation(fig, update, frames=range(1, 8), interval=1000)
plt.show()
which gives the animation from the top of the article. :-)
In conclusion, the Sierpinski Carpet is a fascinating fractal pattern that is made up of smaller and smaller copies of itself. It’s a self-similar shape that looks the same at every level of magnification, and it’s a great example of the beauty and complexity of mathematics. With the help of Python and matplotlib, we can easily visualize this pattern and even animate its construction step by step.