レッスン5:配列にかける公式
Pythonで 「振り子の波」 を作りながら、次のことを学びます:
- 配列全体に当てはめる物理の公式
- すばやく確かめるための np.round と print
- plt.subplots で並べる複数の図
- f文字列
- 位相:振り子が往復のどこにいるか
まず見てみる
クリックするとYouTubeから再生されます。
"""Pendulum wave: 24 pendulums making 51, 52, ... 74 swings in 60 seconds.
Run: python pendulum-wave.py (needs: pip install numpy matplotlib)
"""
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("dark_background")
g, cycle = 9.81, 60.0 # gravity in m/s^2, seconds until they are back in step
n = np.arange(51, 75) # swings per cycle, one more for each pendulum
period = cycle / n
length = g * (period / (2 * np.pi)) ** 2 # small swings: T = 2 pi sqrt(L / g)
print("lengths in cm:", np.round(length * 100, 1))
fig, axes = plt.subplots(1, 4, figsize=(12, 4), sharey=True)
for ax, t in zip(axes, [0, 15, 20, 30]):
swing = np.cos(2 * np.pi * t / period) # where each bob is, from -1 to 1
ax.scatter(swing, np.arange(len(n)), c=swing, cmap="cool", s=40)
ax.set_title(f"t = {t} s")
ax.set_xlim(-1.2, 1.2)
ax.axis("off")
plt.show()
# Try: t = 60 s (or 75, 80, 90): the same pictures again, as every count is whole
このコンピューターにPythonが入っていませんか?ノートブックなら、同じスクリプト、練習問題、答えを、ブラウザ上のGoogle Colabで実行できます。ノートブックは英語です。
1行ずつ
n = np.arange(51, 75)1分あたりの往復回数24通り:51、52、… 74。
period = cycle / n各振り子の周期です。60秒をその回数で割ります。
length = g * (period / (2 * np.pi)) ** 2振れ幅が小さいときの振り子の公式 T = 2π√(L / g) を、長さLについて解いたものです。
fig, axes = plt.subplots(1, 4, figsize=(12, 4), sharey=True)ひとつの図に4つのグラフを横に並べます。ループが時刻ごとにグラフをひとつずつ埋めていきます。
swing = np.cos(2 * np.pi * t / period)時刻tに各おもりがどこにいるか、−1から1まで。t / period 回往復したあとなので、その回数ぶんの回転のコサインです。
ax.set_title(f"t = {t} s")f文字列で、t の値をタイトルに入れます。
やってみよう
いちばん長い振り子といちばん短い振り子は、どれくらいの長さですか?
ヒント
スクリプトが長さを表示します。
答え
1分間に51往復のものが34.4 cm、74往復のものが16.3 cmです。
時刻 t = 12 s を加えてみましょう。列はいくつのグループに分かれますか?
ヒント
5つ目のグラフが必要です:plt.subplots(1, 5) と [0, 12, 15, 20, 30]。
答え
5つです。12秒は1分の5分の1なので、となり同士は往復の5分の1ずつずれています。
振り子を30本にしてみましょう。
ヒント
np.arange の終わりの値を変えます。
答え
n = np.arange(51, 81) で、51から80までの30通りの回数になります。
クイズ
フラッシュカード
表を読み、裏に何があるかを自分で言ってみてから、カードを開いてください。
plt.subplots(1, 4)
ひとつの図と、1列に並んだ4つのグラフ(axes)。ひとつずつ描いていきます。
f"t = {t} s"
f文字列。{t} の場所に t の値が入ります。
振り子の周期
振れ幅が小さいとき、T = 2π√(L / g)。長さが4倍になると、2倍ゆっくりになります。
位相
振り子が往復のどこにいるか。ここでは 2π·t / T のコサイン。
np.round(x, 1)
配列のすべての数を、小数第1位に丸めます。