webmaster-kazu.com

テクノロジー・データ分析・実践ログ・その他

自由落下とpythonプログラム

カテゴリ: Python(遊び)

自由落下に関するpythonプログラムを作ってみます。

なお、初速度 v0 が 0 m/s で、地上から自由落下する物体が 10 秒後にどのくらいの速度に達するかを計算し、結果を表示するPythonプログラムを作ります。

■今回の環境(Python)

今回のPythonは、バージョン3.10.12を用いる。(なお、Google Colaboratory(Google Colab)を使用。)

■結果を表示するPythonプログラム

■コード

# 重力加速度 (m/s²)

g = 9.81

初速度 (m/s)

v0 = 0

時間 (秒)

t = 10

速度を計算

v = v0 + g * t

結果を表示

print("10 秒後の速度は {:.2f} m/s です。".format(v))

■検証、確認

作成したコードは、Google Colaboratoryの新しいノートブック上のセルにコードを記述します。その後「セルを実行」ボタンをクリックします。

先に計算した結果を書くと「98.10 m/s」となります。クリックすると、Google Colaboratory上で処理された結果を確認すると「10 秒後の速度は 98.10 m/s です。」と出力させることができました。

■補足

※速度の時間変化をアニメーションとして描画するためのコード

import matplotlib.pyplot as plt

import numpy as np

from matplotlib.animation import FuncAnimation

重力加速度 (m/s²)

g = 9.81

初速度 (m/s)

v0 = 0

時間 (秒)

t = 10

時間の配列を作成(0からtまで0.1秒刻み)

time = np.arange(0, t, 0.1)

速度の配列を計算

velocity = v0 + g * time

グラフの初期設定

fig, ax = plt.subplots()

ax.set_xlim(0, t)

ax.set_ylim(0, max(velocity) + 1)

line, = ax.plot([], [], lw=2)

アニメーションの初期化

def init():

line.set_data([], [])

return line,

アニメーションのフレーム更新

def update(frame):

x_data = time[:frame]

y_data = velocity[:frame]

line.set_data(x_data, y_data)

return line,

アニメーションの作成

ani = FuncAnimation(fig, update, frames=len(time), init_func=init, blit=True)

アニメーションの表示

plt.xlabel('Time (s)')

plt.ylabel('Velocity (m/s)')

plt.title('Velocity vs. Time')

plt.show()