시어핀스키 삼각형 코딩 - sieopinseuki samgaghyeong koding

거북이 그린 시어핀스키 삼각형

수학 이야기 2017. 7. 25. 16:11

오늘은 거북에게 일을 좀 시켰다. 시어핀스키 삼각형을 그렸다. 시어핀스키 삼각형도 대표적인 프랙탈 도형이다. 만드는 규칙은 간단하다. 아래를 무한 반복하면 얻을 수 있다.

1. 정삼각형에서 세 변의 중심을 연결한다.

2. 가운데 삼각형을 빼낸다.

3. 남아 있는 삼각형에 1,2를 적용한다.

시어핀스키 삼각형 코딩 - sieopinseuki samgaghyeong koding

먼저 1단계 그림을 그리기 위해 함수를 만들었다.

>>> def tri(len):
    for i in range(3):
        t.fd(len)
        t.lt(120)

>>> def tri01(len):
    for i in range(3):
        len=len/2
        t.fd(len)
        t.rt(120)

>>> def sie(len):
    tri(len)
    len=len/2
    t.penup()
    t.lt(60)
    t.fd(len)
    t.rt(60)
    t.pendown()
    tri01(len)
    t.penup()
    t.rt(120)
    t.fd(len)
    t.lt(120)
    t.pendown()

sie(200)

다음으로 무한 반복을 위한 재귀함수를 아래와 같이 정의하였다.

>>>def sietri(len,d):
    if d==1:
        sie(len)
    else:
        len=len/2
        d=d-1
        sietri(len,d)
        t.penup()
        t.fd(len)
        t.pendown()
        sietri(len,d)
        t.penup()
        t.lt(120)
        t.fd(len)
        t.rt(120)
        t.pendown()
        sietri(len,d)
        t.penup()
        t.rt(120)
        t.fd(len)
        t.lt(120)
        t.pendown()

이름은 거북이지만 그래도 상당히 발빠르다. sietri(200,1)은 위에 있는 sie(200)과 똑같다. sietri(200,2)와 sietri(200,3)는 아래와 같다.

sietri(200,2)sietri(200,3)

변수 d가 늘어남에 따라 그려야 하는 삼각형은 기하급수로 늘어난다. sietri(200,6)은 발을 빠르게 놀려도 시간이 걸린다. 기다리다가 한컷 찍었다. 다 그리고 나니 아름답다. 이와 관련된 문제는 시간 관계로 생략한다.

시어핀스키 삼각형 코딩 - sieopinseuki samgaghyeong koding
sietri(200,6)sietri(200,6)

그냥 간단한 문제로 넓이가 $1$인 정삼각형에서 시작했다면 위에 있는 sietri(200,6)에 남아 있는 삼각형 넓이를 모두 더하면 얼마인가 구해보자. 

직관적으로 무한 반복하면 넓이가 어떻게 될까? 이 삼각형은 몇 차원 도형일까?

펜을 들었다 놓았다 하니까 복잡하다. 그냥 재귀함수를 써서 더 단순하게 만들어 보았다. 훨씬 코딩이 간단해서 보기 좋다.

>>>def sier(len,n):
          if n>=1:
                 for i in range(3):
                          t.fd(len)
                          t.lt(120)
                          sier(len/2,n-1)
         else:
                 t.fd(0)

시어핀스키 삼각형 코딩 - sieopinseuki samgaghyeong koding
sier(200,2)
시어핀스키 삼각형 코딩 - sieopinseuki samgaghyeong koding
sier(200,5)
시어핀스키 삼각형 코딩 - sieopinseuki samgaghyeong koding
sier(200,5)

  • 거북수학