python
1''' 2sierpinski.py 3Draw Sierpinski Triangle 4''' 5import random 6import matplotlib.pyplot as plt 7 8def transformation_1(p): 9 x = p[0] 10 y = p[1] 11 x1 = 0.5*x 12 y1 = 0.5*y 13 return x1, y1 14 15def transformation_2(p): 16 x = p[0] 17 y = p[1] 18 x1 = 0.5*x + 0.5 19 y1 = 0.5*y + 0.5 20 return x1, y1 21 22def transformation_3(p): 23 x = p[0] 24 y = p[1] 25 x1 = 0.5*x + 1 26 y1 = 0.5*y 27 return x1, y1 28 29def get_index(probability): 30 r = random.random() 31 c_probability = 0 32 sum_probability = [] 33 for p in probability: 34 c_probability += p 35 sum_probability.append(c_probability) 36 for item, sp in enumerate(sum_probability): 37 if r <= sp: 38 return item 39 return len(probability)-1 40 41def transform(p): 42 # list of transformation functions 43 transformations = [transformation_1, transformation_2, transformation_3] 44 probability = [1/3, 1/3, 1/3] 45 # pick a random transformation function and call it 46 tindex = get_index(probability) 47 t = transformations[tindex] 48 x, y = t(p) 49 return x, y 50 51def draw_sierpinski(n): 52 # We start with (0, 0) 53 x = [0] 54 y = [0] 55 56 x1, y1 = 0, 0 57 for i in range(n): 58 x1, y1 = transform((x1, y1)) 59 x.append(x1) 60 y.append(y1) 61 return x, y 62 63if __name__ == '__main__': 64 n = int(input('Enter the desired number of points' 65 'in the Sierpinski Triangle: ')) 66 x, y = draw_sierpinski(n) 67 # Plot the points 68 plt.plot(x, y, 'o') 69 plt.title('Sierpinski with {0} points'.format(n)) 70 plt.show()
python
1import matplotlib.pyplot as plt 2import random 3 4 5def transform_1(p): 6 x = p[0] 7 y = p[1] 8 x1 = 0.5*x 9 y1 = 0.5*y 10 11 return x1,y1 12 13 14def transform_2(p): 15 x = p[0] 16 y = p[1] 17 x1 = 0.5 * x + 0.5 18 y1 = 0.5 * y + 0.5 19 20 return x1, y1 21 22 23def transform_3(p): 24 x = p[0] 25 y = p[1] 26 27 x1 = 0.5 * x + 1.0 28 y1 = 0.5 * y 29 30 return x1, y1 31 32 33def sierpinski_gasket(n): 34 transformations = [transform_1, transform_2, transform_3] 35 # p[0] = 0 36 # p[1] = 0 37 x = [0] 38 y = [0] 39 40 x1, y1 = 0,0 41 42 while n > 0: 43 rand_index = random.randint(0, 2) 44 t = transformations[rand_index] 45 p = (x1, y1) 46 x1, y1 = t(p) 47 x.append(x1) 48 y.append(y1) 49 n -= 1 50 51 return x, y 52 53 54if __name__ == '__main__': 55 56 n = int(input('試行回数を入力してください')) 57 x, y = sierpinski_gasket(n) 58 ax = plt.axis(xmin=0,ymin=0) 59 plt.plot(x,y,'o') 60 plt.title('sierpinski with {0}point'.format(n)) 61 plt.show() 62
下の図を上の図の正しいシェルピンスキーの三角形にしたいけどやり方がわかりません。どなたか知恵を
貸してください
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/10 04:58