A fractal figure is the same as the original figure no matter how much it is enlarged. The Sierpinski Gasket, which is a typical fractal figure, is shown below.
fractal.py
import matplotlib.pyplot as plt
import matplotlib.patches as pat
import math
#triangle = [(x1,y1),(x2,y2),(x3,y3)]
#Output the coordinates of the triangle in the input triangle
def return_triangle(triangle):
x1 = (triangle[0][0] + triangle[1][0])/2
y1 = (triangle[0][1] + triangle[1][1])/2
x2 = (triangle[1][0] + triangle[2][0])/2
y2 = (triangle[1][1] + triangle[2][1])/2
x3 = (triangle[2][0] + triangle[0][0])/2
y3 = (triangle[2][1] + triangle[0][1])/2
new_triangle = [(x1,y1),(x2,y2),(x3,y3)]
return new_triangle
#Output the distance between two points
def distance(p1,p2):
return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)
#Outputs a triangle consisting of the two points closest to the point p at the points p and the triangle
def select_neighbor_points(p, triangle):
distance1 = distance(p, triangle[0])
distance2 = distance(p, triangle[1])
distance3 = distance(p, triangle[2])
if distance1 > distance2:
if distance1 > distance3:
return [p, triangle[1], triangle[2]]
else:
return [p, triangle[0], triangle[1]]
else:
if distance2 > distance3:
return(p, triangle[0],triangle[2])
else:
return(p, triangle[0],triangle[1])
#Generate a fractal figure. The larger the number of iterations, the more complicated it becomes
def produce_fractal1(triangle, iteration):
if iteration == 0: return 0
p1 = triangle[0]
p2 = triangle[1]
p3 = triangle[2]
new_triangle = return_triangle(triangle)
p = pat.Polygon(xy = new_triangle,fc = "white", ec = "black")
ax.add_patch(p)
produce_fractal1(select_neighbor_points(p1,new_triangle), iteration-1)
produce_fractal1(select_neighbor_points(p2,new_triangle), iteration-1)
produce_fractal1(select_neighbor_points(p3,new_triangle), iteration-1)
triangle = [(0.2, 0.2), (0.8, 0.2), (0.5, 0.8)] #Coordinates of the initial triangle
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(1,1,1)
p = pat.Polygon(xy = triangle,fc = "white", ec = "black")
ax.add_patch(p)
produce_fractal1(triangle,6)
fig.savefig("./fractal.png ") #Save image
It can be easily implemented by recursive processing. Execution was done by jupyter.
fractal.py
produce_fractal1(triangle,iteration)
Increasing the number of iterations creates triangles deeper.
By implementing recursive processing well, we were able to create a Sierpinski Gasket. By changing the contents of recursive processing, we can create other fractal figures.
Recommended Posts