I have a function in SQL Server that calculates the distance between two specified points.
The function uses an implementation of the Haversine formula written as a function in T-SQL:
CREATE FUNCTION dbo.mpl_geo_distance
(
@LAT1 FLOAT ,
@LON1 FLOAT ,
@LAT2 FLOAT ,
@LON2 FLOAT
)
RETURNS FLOAT
WITH ENCRYPTION
AS
BEGIN
DECLARE @A AS FLOAT
DECLARE @C AS FLOAT
DECLARE @L1 AS FLOAT
DECLARE @L2 AS FLOAT
DECLARE @R1 AS FLOAT
DECLARE @R2 AS FLOAT
SET @R1 = RADIANS(@LAT1)
SET @R2 = RADIANS(@LAT2)
SET @L1 = RADIANS(@LAT2 - @LAT1)
SET @L2 = RADIANS(@LON2 - @LON1)
SET @A = SIN(@L1 / 2) * SIN(@L1 / 2) + COS(@R1) * COS(@R2) * SIN(@L2 / 2) * SIN(@L2 / 2)
SET @C = 2 * ATN2(SQRT(@A), SQRT(1 - @A))
RETURN 6371000 * @C
END
Following some answers I read on SO, I decided to try to make use of the GEOGRAPHY
type and the STDistance
. However, the results of both methods are different (although not by much):
-- Distance between London and Eiffel Tower
DECLARE @X GEOGRAPHY = 'POINT(51.5000 -0.1300)'
DECLARE @Y GEOGRAPHY = 'POINT(48.858093 2.294694)'
PRINT @X.STDistance(@Y)
PRINT dbo.mpl_geo_distance (51.5000, -0.1300, 48.858093, 2.294694)
Yields:
397909
340704
Which value is the more accurate and which should I use?
答案 0 :(得分:1)
The Haversine formula is an estimation. If you have a look at this site, it shows various calculations, but notes:
All these formulæ are for calculations on the basis of a spherical earth (ignoring ellipsoidal effects) – which is accurate enough* for most purposes… [In fact, the earth is very slightly ellipsoidal; using a spherical model gives errors typically up to 0.3% – see notes for further details].
Wikipedia claims the error can be even higher:
Either formula is only an approximation when applied to the Earth, which is not a perfect sphere: the "Earth radius" R varies from 6356.752 km at the poles to 6378.137 km at the equator. More importantly, the radius of curvature of a north-south line on the earth's surface is 1% greater at the poles (≈6399.594 km) than at the equator (≈6335.439 km)— so the haversine formula and law of cosines can't be guaranteed correct to better than 0.5%
After having a dig around, I'm not entirely sure exactly how STDistance calculates things, but Microsoft say this:
STDistance() returns the shortest LineString between two geography types. This is a close approximate to the geodesic distance. The deviation of STDistance() on common earth models from the exact geodesic distance is no more than .25%. This avoids confusion over the subtle differences between length and distance in geodesic types.
If the various sources are to be believed, then it seems that STDistance is likely to be more accurate than the Haversine formula.