開発環境
- macOS High Sierra - Apple
- Emacs (Text Editor)
- Python 3.7 (プログラミング言語)
Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の2章(データをグラフで可視化する)、2.6(プログラミングチャレンジ)、問題2-3(投射軌跡比較プログラムの拡張)を取り組んでみる。
コード(Emacs)
Python 3
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import math
g = 9.8
def sx(u, theta, t):
theta = math.radians(theta)
return u * math.cos(theta) * t
def sy(u, theta):
theta = math.radians(theta)
t_peak = u * math.sin(theta) / g
return u * math.sin(theta) * t_peak - 1 / 2 * g * t_peak ** 2
def t_flight(u, theta):
theta = math.radians(theta)
return 2 * 5 * math.sin(theta)
def draw_graph(x, y):
plt.plot(x, y)
plt.xlabel('x-coordinate')
plt.ylabel('y-coordinate')
plt.title('Projectile motion of a ball')
def frange(start, stop, step):
res = []
while start < stop:
res.append(start)
start += step
return res
def draw_trajectory(u, theta):
theta = math.radians(theta)
t_flight = 2 * u * math.sin(theta) / g
intervals = frange(0, t_flight, 0.001)
x = [u * math.cos(theta) * t for t in intervals]
y = [u * math.sin(theta) * t - 0.5 * g * t * t for t in intervals]
draw_graph(x, y)
if __name__ == '__main__':
try:
n = int(input('How many trajectories'))
u_list = []
for _ in range(n):
try:
u = float(input('Enter the initial velocity (m/s): '))
theta = float(
input('Enter the angle of projection (degrees): '))
except ValueError:
print('You entered an invalid input')
else:
u_list.append(u)
t = t_flight(u, theta)
with open('output3.txt', 'a') as f:
print(
f'飛行時間: {t}, 最大水平距離: {sx(u, theta, t)}, 最大垂直距離: {sy(u, theta)}',
file=f)
draw_trajectory(u, theta)
plt.legend(u_list)
plt.savefig('sample3.svg')
except ValueError:
print('You entered an invalid input')
入出力結果(Terminal, Jupyter(IPython))
$ ./sample3.py < input.txt How many trajectoriesEnter the initial velocity (m/s): Enter the angle of projection (degrees): Enter the initial velocity (m/s): Enter the angle of projection (degrees): Enter the initial velocity (m/s): Enter the angle of projection (degrees): $ cat output3.txt 飛行時間: 7.071067811865475, 最大水平距離: 225.0, 最大垂直距離: 51.658163265306115 飛行時間: 7.071067811865475, 最大水平距離: 300.0, 最大垂直距離: 91.83673469387753 飛行時間: 10.0, 最大水平距離: 2.7554552980815446e-14, 最大垂直距離: 103.31632653061223 $
0 コメント:
コメントを投稿