要求:地球的平均半徑為6371千米,已知地球上兩個城市A、B的經度和緯度,編程式求出這兩個城市之間的地面距離。
首先,固定兩點,a(x1,y1,z1),b(x2,y2,z2)。
由空間解析幾何及向量知識知:
其中,theta是兩向量夾角,球面距離d:
對於A點來說(圖中a應改為A,畫圖的時候寫錯了),
theta就是A點的緯度值,即:
也即:
而對於A點的x,y座標,首先:
r1是小圓的半徑,也就是中的藍色圓:
請注意平面圖與立體圖中座標的對應,我已一一對應好,注意觀察。
圖中的alpha即:
所以,座標與經度之間有如下關係:
實際的北極點是這樣的:
還有一點,東西經南北緯轉化問題。
關於東西經和南北緯,在上面的闡述中,東經的點的y值都是正值,西經的點的y值都是負值,北緯的點的z值都是正值,南緯的點的z值都是負值。因為如,地球被分為了東北半球,東南半球,西北半球,西南半球:
如上分析,不難寫出如下代碼:
#include <iostream>#include <cmath>#include <string>#include <cstring>#include <cstdio>using namespace std;#define pi 3.1415926535#define radio 6378137.0//defining a new struct for the convenience of calculatingtypedef struct{ long double Longitude; long double Lantitude; string East_or_West; string North_or_South;} dot;//function for calculatingint Distance(float lat1, float lon1, float lat2, float lon2){ double latitude1,longitude1,latitude2,longitude2; double dlat,dlon; latitude1=lat1; longitude1=lon1; latitude2=lat2; longitude2=lon2; //computing procedure double a,c,distance; dlon =fabs((longitude2 - longitude1))*pi/180; dlat =fabs((latitude2 - latitude1))*pi/180; a = (sin(dlat/2)*sin(dlat/2)) + cos(latitude1*pi/180) * cos(latitude2*pi/180) * (sin(dlon/2)*sin(dlon/2)); if(a==1.0) c=pi; else c = 2 * atan(sqrt(a)/sqrt(1-a)); distance= radio*c; return distance;}int main(){ long double r = 6371.004; dot a, b; //freopen("D:\example.txt","r",stdin); while(1) { cout<<"Please input the two dots' coordinates like the following format: "<<endl; cout<<"East 30 North 20"<<"West 40 North 10"<<endl; //data input procedure cin>>a.East_or_West>>a.Longitude>>a.North_or_South>>a.Lantitude; cin>>b.East_or_West>>b.Longitude>>b.North_or_South>>b.Lantitude; //transfer { if(a.East_or_West == "East") { a.Longitude = a.Longitude; } else if(a.East_or_West == "West") { a.Longitude = - a.Longitude; } } { if(a.North_or_South == "North") { a.Lantitude = pi / 2 - a.Lantitude; } else if (a.North_or_South == "South") { a.Lantitude = pi / 2 + a.Lantitude; } } { if(b.East_or_West == "East") { b.Longitude = b.Longitude; } else if(a.East_or_West == "West") { b.Longitude = - b.Longitude; } } { if(a.North_or_South == "North") { b.Lantitude = pi / 2 - b.Lantitude; } else if (a.North_or_South == "South") { b.Lantitude = pi / 2 + b.Lantitude; } } //data output procedure float result = Distance(a.Lantitude, a.Longitude, b.Lantitude, b.Longitude); cout<<"The distance is: "<<result<<endl<<endl; }}
可能有所紕漏,因為第一遍寫代碼的時候沒這麼仔細分析。
想要更深層次瞭解此問題,請參看微分幾何中關於測地線及測地線曲率的相關問題。
欲證明該思想的正確性,可以採取如下反證法:
假設通過二點存在一個小圓對應的劣弧長比球面距離小,那條曲線未必是平面曲線,所以未必是圓弧。