2016年9月1日木曜日

開発環境

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

問題6-4(マンデルブロを集合を描く)

コード(Emacs)

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

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib import animation


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

XMIN = -2.5
XMAX = 1.0
YMIN = -1.0
YMAX = 1.0
MAX_ITERATION = 1000


def draw_mandelbrot_set(x_p, y_p):
    fig = plt.figure(figsize=(5, 5))
    image = initialize_image(x_p, y_p)
    dx = (XMAX - XMIN) / (x_p - 1)
    dy = (YMAX - YMIN) / (y_p - 1)
    xs = [XMIN + i * dx for i in range(x_p)]
    ys = [YMIN + i * dy for i in range(y_p)]
    for i, x in enumerate(xs):
        for k, y in enumerate(ys):
            z1 = 0
            c = x + y * 1j
            iteration = 0
            while (abs(z1) < 2) and (iteration < MAX_ITERATION):
                z1 = z1**2 + c
                iteration += 1
            image[k][i] = iteration

    plt.imshow(image, origin='lower', extent=(XMIN, XMAX, YMIN, YMAX),
               cmap=cm.Greys_r, interpolation='nearest')
    plt.savefig('mandelbrot_set.png')
    plt.show()

if __name__ == '__main__':
    x_p = 400
    y_p = 400
    draw_mandelbrot_set(x_p, y_p)

入出力結果(Terminal, IPython)

$ ./sample4.py
$

1 コメント :

匿名さんのコメント...

美しいですね

コメントを投稿