開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の2章(データをグラフで可視化する)、2.6(プログラミングチャレンジ)、問題2-3(投射軌跡比較プログラムの拡張)を取り組んでみる。
問題2-3(投射軌跡比較プログラムの拡張)
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import math
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, final, interval):
numbers = []
while start < final:
numbers.append(start)
start += interval
return numbers
def draw_trajectory(u, theta, t_flight):
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__':
plt.figure(figsize=(5, 5))
g = 9.8
velocities = []
angles = []
try:
n = int(input('How many trajectories? '))
for i in range(n):
u = float(
input('Enter the initial velocity {0} (m/s): '.format(i + 1))
)
theta = float(
input(
'Enter the angle of projection {0} (degrees): '.format(
i + 1
)
)
)
velocities.append(u)
angles.append(theta)
except ValueError as err:
print('You entered an invalid input')
print(err)
else:
legends = []
for i, velocity in enumerate(velocities):
angle = angles[i]
rad = math.radians(angle)
legends.append((velocity, angle))
t_flight = 2 * velocity * math.sin(rad) / g
x = velocity * math.cos(rad) * t_flight
t = t_flight / 2
y = velocity * math.sin(rad) * t - 0.5 * g * t * t
print('velocity: {0}, angle: {1}\n\ttime: {2}, x: {3}, y:{4}'.
format(velocity, angle, t_flight, x, y))
draw_trajectory(velocity, rad, t_flight)
plt.legend(legends)
plt.savefig('trajectory.png')
plt.show()
入出力結果(Terminal, IPython)
$ ./sample3.py How many trajectories? 3 Enter the initial velocity 1 (m/s): 45 Enter the angle of projection 1 (degrees): 45 Enter the initial velocity 2 (m/s): 60 Enter the angle of projection 2 (degrees): 45 Enter the initial velocity 3 (m/s): 45 Enter the angle of projection 3 (degrees): 80 velocity: 45.0, angle: 45.0 time: 6.493837786407068, x: 206.6326530612245, y:51.658163265306115 velocity: 60.0, angle: 45.0 time: 8.65845038187609, x: 367.3469387755101, y:91.83673469387752 velocity: 45.0, angle: 80.0 time: 9.044152833785583, x: 70.6725296157632, y:100.20095808906795 $
0 コメント:
コメントを投稿