1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでフラクタル図形を作成part1(シェルピンスキーのギャスケット)

Posted at

#1.フラクタル図形とは
フラクタル図形とは,どんなに拡大しても元々の図形と同じであるもの.
フラクタル図形の代表的なものであるシェルピンスキーのギャスケットを以下に示す.
fractal1.gif

#2.シェルピンスキーのギャスケットの作成

fractal.py
import matplotlib.pyplot as plt
import matplotlib.patches as pat
import math

#triangle = [(x1,y1),(x2,y2),(x3,y3)]

#入力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

#2点間の距離を出力する
def distance(p1,p2):
    return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)

#点pとtriangleの内の点で点pに最も近い2点から構成される三角形を出力
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])
            
#fractal図形を生成する。iteration数が大きいほど複雑になる
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)] #初期三角形の座標
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") #画像の保存

再帰処理で簡単に実装できる.実行はjupyterで行った.

fractal.py
produce_fractal1(triangle,iteration)

iterationの数を大きくするとより深い層まで三角形がつくられる.

#3.まとめ
再帰処理をうまく実装することでシェルピンスキーのギャスケットを作ることができた.再帰処理の中身を変えることで他のフラクタル図形を作成できる.

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?