開発環境
- 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 #4: Drawing the Mandelbrot Set, (No. 4122)を取り組んでみる。
Programming Challenges #4: Drawing the Mandelbrot Set, (No. 4122)
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import random
def initialize_image(x_p, y_p):
image = []
for _ in range(y_p):
x_colors = []
for _ in range(x_p):
x_colors.append(0)
image.append(x_colors)
return image
def color_points():
MAX_ITERATION = 1000
x_p = 400
y_p = 400
image = initialize_image(x_p, y_p)
x_p1 = [-2.5 + (1.0 - -2.5) / (x_p - 1) * x for x in range(x_p)]
y_p1 = [-1.0 + (1.0 - -1.0) / (y_p - 1) * y for y in range(y_p)]
for i, x in enumerate(x_p1):
if i % 10 == 0:
print(i)
if i % 100 == 0:
plt.imshow(image, origin='lower', extent=(-2.5, 1.0, -1.0, 1.0),
cmap=cm.Greys_r, interpolation='nearest')
plt.title('Mandelbrot Set_{0}'.format(i))
plt.savefig('mandelbrot_set_{0}.png'.format(i))
for k, y in enumerate(y_p1):
z1 = 0 + 0j
c = complex(x, y)
iteration = 0
z1 = z1 ** 2 + c
iteration += 1
while abs(z1) < 2 and iteration < MAX_ITERATION:
z1 = z1 ** 2 + c
iteration += 1
image[k][i] = iteration
plt.imshow(image, origin='lower', extent=(-2.5, 1.0, -1.0, 1.0),
cmap=cm.Greys_r, interpolation='nearest')
plt.title('Mandelbrot Set')
plt.savefig('mandelbrot_set.png')
plt.show()
if __name__ == '__main__':
color_points()
入出力結果(Terminal, IPython)
$ ./sample4.py 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200 210 220 230 240 250 260 270 280 290 300 310 320 330 340 350 360 370 380 390 $
0 コメント:
コメントを投稿