# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # The chaos game and the Sierpinski triangle
#
# Source: https://www.johndcook.com/blog/2017/07/08/the-chaos-game-and-the-sierpinski-triangle/
#
# TODO: https://twitter.com/franssoa/status/1102223543897636865

from scipy import sqrt, zeros
import matplotlib.pyplot as plt
from random import random, randint


def midpoint(p, q):
    return (0.5*(p[0] + q[0]), 0.5*(p[1] + q[1]))


# +
# Three corners of an equilateral triangle
corner = [(0, 0), (0.5, sqrt(3)/2), (1, 0)]

N = 1000
x = zeros(N)
y = zeros(N)

x[0] = random()
y[0] = random()
for i in range(1, N):
    k = randint(0, 2) # random triangle vertex
    x[i], y[i] = midpoint( corner[k], (x[i-1], y[i-1]) )
# -

plt.scatter(x, y)
plt.show()

StarcoderdataJupyterScriptsDedupFiltered