2016年3月9日水曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 6.(Drawing Geometric Shapes and Fractals)、Programming Challenges #2: Drawing the Sierpiński Triangle, (No. 4091)を取り組んでみる。

Programming Challenges #2: Drawing the Sierpiński Triangle, (No. 4091)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random
from matplotlib import pyplot as plt

# AX = plt.axes(xlim=(1, 5), ylim=(1, 5))

def transformation_1(p):
    x = p[0]
    y = p[1]
    x1 = 0.5 * x
    y1 = 0.5 * y
    return x1, y1

def transformation_2(p):
    x = p[0]
    y = p[1]
    x1 = 0.5 * x + 0.5
    y1 = 0.5 * y + 0.5
    return x1, y1

def transformation_3(p):
    x = p[0]
    y = p[1]
    x1 = 0.5 * x + 1
    y1 = 0.5 * y
    return x1, y1

def get_index(probability):
    r = random.random()
    c_probability = 0
    sum_probability = []
    for p in probability:
        c_probability += p
        sum_probability.append(c_probability)
    for item, sp in enumerate(sum_probability):
        if r <= sp:
            return item
    return len(probability) - 1
        
def transform(p):
    transformations = [transformation_1, transformation_2, transformation_3]
    probability = [1/3, 1/3, 1/3]
    tindex = get_index(probability)
    t = transformations[tindex]
    x, y = t(p)
    return x, y

def draw_sierpinski_triangle(n):
    x = [0]
    y = [0]

    x1, y1 = 0, 0
    for i in range(n):
        x1, y1 = transform((x1, y1))
        x.append(x1)
        y.append(y1)
    return x, y

if __name__ == '__main__':
    n = int(input('Enter the number of points: '))
    x, y = draw_sierpinski_triangle(n)
    plt.plot(x, y, 'o')
    plt.title('Sierpiński Triangle with {0} points'.format(n))
    plt.savefig('sierpinski_triangle_{0}.png'.format(n))
    plt.show()

入出力結果(Terminal, IPython)

$ ./sample2.py
Enter the number of points: 10
$ ./sample2.py
Enter the number of points: 100
$ ./sample2.py
Enter the number of points: 1000
$ ./sample2.py
Enter the number of points: 10000
$ ./sample2.py
Enter the number of points: 5000
$

0 コメント:

コメントを投稿

Comments on Google+: