開発環境
- macOS High Sierra - Apple
- Emacs (Text Editor)
- Python 3.6 (プログラミング言語)
Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の2章(データをグラフで可視化する)、2.6(プログラミングチャレンジ)、問題2-3(投射軌跡比較プログラムの拡張)を取り組んでみる。
コード(Emacs)
Python 3
#!/usr/bin/env python3 import math from matplotlib import pyplot as plt 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): theta = math.radians(theta) g = 9.8 t_flight = 2 * u * math.sin(theta) / g intervals = frange(0, t_flight, 0.001) x = [] y = [] for t in intervals: x.append(u * math.cos(theta) * t) y.append(u * math.sin(theta) * t - 0.5 * g * t * t) draw_graph(x, y) if __name__ == '__main__': n = 0 while n == 0: try: n = int(input('How many trajectories? ')) except Exception as err: print(type(err), err) i = 1 while i <= n: try: u = float(input(f'Enter the initial velocity {i}(m/s): ')) theta = float( input(f'Enter the angle of projection {i}(degrees): ')) except ValueError: print('You entered an invalid input') else: draw_trajectory(u, theta) i += 1 plt.savefig('sample3.svg')
入出力結果(Terminal, Jupyter(IPython))
$ ./sample3.py How many trajectories? a <class 'ValueError'> invalid literal for int() with base 10: 'a' How many trajectories? 3 Enter the initial velocity 1(m/s): a You entered an invalid input 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): a You entered an invalid input Enter the initial velocity 3(m/s): 45 Enter the angle of projection 3(degrees): 90 $
0 コメント:
コメントを投稿