2018年6月20日水曜日

開発環境

Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の6章(幾何図形とフラクタルを描画する)、5.4(プログラミングチャレンジ)、問題6-4(マンデルブロ集合を描く)を取り組んでみる。

コード(Emacs)

Python 3

#!/usr/bin/env python3
import matplotlib.pyplot as plt
import matplotlib.cm as cm


def initialize_image(x_p, y_p):
    image = [[0 for j in range(x_p)]
             for i in range(y_p)]
    return image


def mandelbrot_set():
    x1, y1 = (-2.5, -1.0)
    x2, y2 = (1, 1)
    x_p = 400
    y_p = 400
    dx = (x2 - x1) / x_p
    dy = (y2 - y1) / y_p
    xs = [x1 + i * dx for i in range(x_p)]
    ys = [y1 + i * dy for i in range(y_p)]
    image = initialize_image(x_p, y_p)
    max_iteration = 100
    for i, x in enumerate(xs):
        for k, y in enumerate(ys):
            z1 = 0 + 0j
            c = x + y * 1j
            iteration = 0
            z1 = z1 ** 2 + c
            while abs(z1) < 2 and iteration < max_iteration:
                z1 = z1 ** 2 + c
                iteration += 1
            image[k][i] = iteration
    plt.imshow(image, origin='lower', extent=(x1, x2, y1, y2),
               cmap=cm.Greys_r, interpolation='nearest')
    plt.savefig('sample4.svg')
    plt.show()


if __name__ == '__main__':
    mandelbrot_set()

入出力結果(Terminal, Jupyter(IPython))

$ ./sample4.py
$

0 コメント:

コメントを投稿