Sierpinski’s triangle and friends

import numpy as np
import matplotlib.pyplot as plt

def sierpinski(n_vert, n_iter, **kwargs):
    vertices = [
        np.array([np.cos(theta), np.sin(theta)])
        for theta in np.pi/2 + np.linspace(0, 2*np.pi, n_vert, endpoint=False)
    pos = vertices[0]

    history = []
    for i in range(n_iter):
        destination = vertices[np.random.randint(0, n_vert)]
        delta = destination - pos
        pos = pos + delta/2

    data = np.stack(history)

    fig, ax = plt.subplots()
    plt.scatter(data[:, 0], data[:, 1], s=1, **kwargs)
    return fig
sierpinski(n_vert=3, n_iter=5000).show()
sierpinski polygons
sierpinski(n_vert=5, n_iter=200000, alpha=0.1).show()
sierpinski polygons

Total running time of the script: ( 0 minutes 3.120 seconds)

Gallery generated by Sphinx-Gallery