数学と日付時刻を使った航海
このステップでは、近い将来の旅のコースを計画する任務が与えられます。math
モジュールを使って最適なルートを計算し、datetime
モジュールの助けを借りて到着時刻を推定します。
まず、~/project
ディレクトリにあるchart_course.py
という名前のスクリプトを開きます。このスクリプトは、緯度と経度の座標に基づいて次の目的地までの距離を計算します。
import math
## 現在の位置と目的地の座標(度)
current_location = (0, 0)
destination = (10, 10)
def calculate_distance(loc1, loc2):
## 度をラジアンに変換
lat1, lon1 = map(math.radians, loc1)
lat2, lon2 = map(math.radians, loc2)
## ヘイバーシン公式
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
r = 6371 ## 地球の半径(キロメートル)
return c * r
## 距離を推定
distance = calculate_distance(current_location, destination)
print(f"目的地までの距離は{distance:.2f}キロメートルです。")
次に、datetime
を使って到着時刻を推定します。
from datetime import datetime, timedelta
## 平均船速を10km/hとする
average_speed = 10
## 到着時刻を計算
time_to_destination = timedelta(hours=distance / average_speed)
arrival_time = datetime.now() + time_to_destination
print(f"推定到着時刻: {arrival_time.strftime('%Y-%m-%d %H:%M:%S')}")
ターミナルで次のコマンドを実行してスクリプトを実行します。
python ~/project/chart_course.py
ターミナルには次の情報が表示されるはずです。
目的地までの距離は1568.52キロメートルです。
推定到着時刻: 2024-01-04 09:40:36