放物線軌道のPythonコード

放物運動の軌道をPythonで出力してみよう。

数学的解説

放物運動とは投射角度 $\theta$, 初速度 $v_0$ に対して, $$x = v_x t, \ \ y= v_y t - \frac{1}{2} g t^2$$ で表せる運動のことである。ただし, $v_x = v_0 \cos \theta$, $v_y = v_0 \sin \theta$ であり, 重力加速度を $g$ とした。この軌道は放物線を描く。

Pythonコード.

import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# 放物運動をシミュレートする関数
def 放物運動(v, theta, g):
    theta_rad = math.radians(theta)
    vx = v * math.cos(theta_rad)
    vy = v * math.sin(theta_rad)
    t_flight = (2 * vy) / g
    dt = 0.01
    t = np.arange(0, t_flight, dt)
    x = vx * t
    y = vy * t - 0.5 * g * t ** 2
    return x, y

# 入力パラメータ
v0 = 20  # 初速度(m/s)
角度 = 45  # 射角(度)
g = 9.81  # 重力加速度(m/s^2)

# 放物運動をシミュレート
x, y = 放物運動(v0, 角度, g)

# グラフと軸を作成
fig, ax = plt.subplots()
ax.set_xlim(0, max(x) + 5)
ax.set_ylim(0, max(y) + 5)
line, = ax.plot([], [], lw=2)

# アニメーション関数
def アニメーション(i):
    line.set_data(x[:i], y[:i])
    return line,

# アニメーションを作成
ani = animation.FuncAnimation(fig, アニメーション, frames=len(x), interval=10, blit=True)

# アニメーションをHTML5ビデオとして保存して表示
HTML(ani.to_html5_video())

※ChatGPTで作成しました。

出力結果

「入力パラメータの数値」を変えれば、他の放物線軌道のアニメーションができます。

コメントを残す