プログラミング入門II 宿題 2025.07.16

Back


乱数により発生させた4から8までの整数を半径とする円を描く動画を作成しましょう.単純な再描画でも可能ですし,アニメーション機能を使用しても作成できます.今回はどちらでも構いません.

上の実行例は下記のようにいくつかの「技」を使用して作成しています.

方法ですが,円弧を描くので,小さな角度ずつ点を回転させました.0 から 2π までだと最後にちょっと線がつながらない部分が見えてしまうので,ちょっとだけ余分に角度を進めています.
解答用紙を使用する際には,学生番号と名前の記入も忘れないでください.さらに,解答用紙自体がPythonのプログラムとなっていますので,実行してエラーの無いことを確認してから提出してください.

指定の解答用紙を使用していない,実行時にエラーが出る,学生番号と名前が無い,というような答案は提出されても採点しません.注意してください.


解答例

# #############################
#
# プログラミング入門II 宿題 2025.7.16
# 学生番号:  s246099
# 氏名:     松江 花子
#
# #############################

from random import *
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator

r = randint(4, 8)

txt = f'Circle of radius {r}\ns246099'

theta = 0
th = []
x = []
y = []

fig, ax = plt.subplots()

ax.set_ylabel('y')
ax.set_xlabel('x')
ax.set_xlim(-9, 9)
ax.set_ylim(-9, 9)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_aspect('equal', adjustable='box')
ax.grid()

ax.text(0.03, 0.87, txt,  transform=ax.transAxes)

while theta <= np.pi * 2 + 0.1:
    th.append(theta)
    x.append(r * np.cos(theta))
    y.append(r *np.sin(theta))
    line, = ax.plot(x, y)

    plt.tight_layout()
    plt.pause(0.1)

    theta += 0.1

# ------ End of text -------
# #############################
#
# プログラミング入門II 宿題 2025.7.16
# 学生番号:  s246099
# 氏名:     松江 花子
#
# #############################

from random import *
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
from matplotlib.ticker import MaxNLocator
from matplotlib.animation import PillowWriter
from time import *

def graph_update(data):
    xx, yy = data

    x.append(xx)
    y.append(yy)

    line.set_data(x, y)

    return [line]

def graph():
    ax.set_ylabel('y')
    ax.set_xlabel('x')
    ax.set_xlim(-9.5, 9.5)
    ax.set_ylim(-9.5, 9.5)
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax.set_aspect('equal', adjustable='box')

    ax.text(0.03, 0.87, txt, transform=ax.transAxes)
    ax.set_aspect('equal', adjustable='box')

    line.set_data(x, y)

    return [line]

def make_data():
    theta = 0

    while theta <= np.pi * 2 + 0.5:
        xx = np.cos(theta) * r
        yy = np.sin(theta) * r

        yield xx, yy

        theta += 0.1

        sleep(0.01)    

r = randint(4, 8)

txt = f'Circle of radius {r}\ns246099'

fig, ax = plt.subplots()

line, = ax.plot([], [])
x, y = [], []

ax.grid()

ani = animation.FuncAnimation(fig, graph_update, make_data,
                              blit=True, interval=100,
                              cache_frame_data = False,
                              repeat=False, init_func=graph)

plt.show()

# ------ End of text -------
再描画アニメーション

Back