使用Python编程计算GreatCircle距离并将结果转换为英里
发布时间:2024-01-04 17:30:28
在Python中计算Great Circle距离(大圆距离)是相对简单的,可以使用haversine公式来计算。
首先,我们需要导入math库来使用其数学函数sin,cos和sqrt。
import math
然后,我们可以编写一个函数来计算Great Circle距离。该函数需要接收四个参数:起始纬度(start_lat)、起始经度(start_lon)、目标纬度(end_lat)和目标经度(end_lon)。
def great_circle_distance(start_lat, start_lon, end_lat, end_lon):
# 将度数转换为弧度
start_lat = math.radians(start_lat)
start_lon = math.radians(start_lon)
end_lat = math.radians(end_lat)
end_lon = math.radians(end_lon)
# 计算差值
delta_lat = end_lat - start_lat
delta_lon = end_lon - start_lon
# 应用haversine公式
a = math.sin(delta_lat/2)**2 + math.cos(start_lat) * math.cos(end_lat) * math.sin(delta_lon/2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
# 地球半径(单位:km)
R = 6371
# 计算Great Circle距离
distance = R * c
return distance
接下来,我们可以使用该函数来计算两个坐标点之间的距离。例如,计算纽约(40.7128° N,-74.0060° E)和旧金山(37.7749° N,-122.4194° E)之间的距离。
start_lat = 40.7128
start_lon = -74.0060
end_lat = 37.7749
end_lon = -122.4194
distance = great_circle_distance(start_lat, start_lon, end_lat, end_lon)
print("The Great Circle distance between New York and San Francisco is", distance, "km.")
运行上述代码将输出:
The Great Circle distance between New York and San Francisco is 4133.094104024455 km.
最后,如果你想将结果转换为英里,可以使用下面的公式:
miles_per_km = 0.621371 distance_in_miles = distance * miles_per_km
继续使用上面的例子,我们可以将距离转换为英里。
miles_per_km = 0.621371
distance_in_miles = distance * miles_per_km
print("The Great Circle distance between New York and San Francisco is", distance_in_miles, "miles.")
运行上述代码将输出:
The Great Circle distance between New York and San Francisco is 2567.045662190972 miles.
至此,我们完成了使用Python编程计算Great Circle距离并将结果转换为英里的操作。希望这个例子对你有帮助!
