|
| 1 | + |
| 2 | +# coding: utf-8 |
| 3 | + |
| 4 | +# In[1]: |
| 5 | + |
| 6 | + |
| 7 | +#fractal is one of the interesting topics in geometry |
| 8 | +#it is usually described by a recursive function |
| 9 | +#voila,here we are! |
| 10 | +import matplotlib.pyplot as plt |
| 11 | + |
| 12 | + |
| 13 | +# In[2]: |
| 14 | + |
| 15 | + |
| 16 | +#initialize |
| 17 | +x1=0 |
| 18 | +x2=3 |
| 19 | +y=0 |
| 20 | +bar_height=5 |
| 21 | +between_interval=10 |
| 22 | +n=6 |
| 23 | + |
| 24 | + |
| 25 | +# In[3]: |
| 26 | + |
| 27 | + |
| 28 | +#cantor set is one of the simplest fractal shape |
| 29 | +#at each iteration,we divide each bar into three equal parts |
| 30 | +#we remove the mid part from each bar and keep the rest |
| 31 | +#this effectively creates a binary tree |
| 32 | +#check the link below for more details on math |
| 33 | +# https://www.math.stonybrook.edu/~scott/Book331/Cantor_sets.html |
| 34 | +def cantor_set(x1,x2,y,n, |
| 35 | + bar_height=5,between_interval=10): |
| 36 | + |
| 37 | + #base case |
| 38 | + if n==0: |
| 39 | + return |
| 40 | + |
| 41 | + else: |
| 42 | + |
| 43 | + #viz the first 1/3 and the last 1/3 |
| 44 | + plt.fill_between([x1,x1+(x2-x1)/3], |
| 45 | + [y-between_interval]*2, |
| 46 | + [y-bar_height-between_interval]*2,) |
| 47 | + plt.fill_between([x2-(x2-x1)/3,x2], |
| 48 | + [y-between_interval]*2, |
| 49 | + [y-bar_height-between_interval]*2,) |
| 50 | + |
| 51 | + #recursion |
| 52 | + cantor_set(x1,x1+(x2-x1)/3, |
| 53 | + y-between_interval, |
| 54 | + n-1) |
| 55 | + cantor_set(x2-(x2-x1)/3,x2, |
| 56 | + y-between_interval, |
| 57 | + n-1) |
| 58 | + |
| 59 | + |
| 60 | +# In[4]: |
| 61 | + |
| 62 | + |
| 63 | +#viz |
| 64 | +#as n increases |
| 65 | +#the bar gets too slim to be visible |
| 66 | +ax=plt.figure(figsize=(10,10)) |
| 67 | +plt.fill_between([x1,x2], |
| 68 | + [y]*2, |
| 69 | + [y-bar_height]*2,) |
| 70 | +cantor_set(x1,x2,y,n) |
| 71 | +plt.axis('off') |
| 72 | +plt.show() |
| 73 | + |
0 commit comments