Fastest way to reduce number of latitude and longitude points

后端 未结 3 1654
攒了一身酷
攒了一身酷 2021-02-20 04:24

I\'m trying to reduce and combine a number of points to the center point of those locations. Right now I\'m brute-forcing it by finding the closest pair, combining those and re

3条回答
  •  余生分开走
    2021-02-20 05:16

    To speed up working out distances between points:

    If you do some elementary algebra you get:

    D = R*Sqrt(Lat2^2 + Lat1^2 - 2*Lat1*Lat2 + cos^2((Lat2 + Lat1) /2)(Lon2^2 + Lon1^2 - 2*Lon1*Lon2))
    

    The first thing you can do to speed this up is normalise to the radius of the Earth (R) and compare squared distances rather than distances, thus avoiding the square root and R term, saving yourself 2 calculations per comparison. Leaving:

    valToCompare = Lat2^2 + Lat1^2 - 2*Lat1*Lat2 + cos^2((Lat2 + Lat1) /2)(Lon2^2 + Lon1^2 - 2*Lon1*Lon2)
    

    Another thing you could do is precalculate Lat^2 and Lon^2 for each coordinate - reducing the number of calculations for each comparison by 4.

    Further, if the points are all relatively close together in latitude you could take an approximation for the cos^2 term by precalculating it using the latitude of a random point or the average latitude of all the points, rather than the average latitude of the two points being compared. This reduces the number of calculations for each comparison by another 4.

    Finally, you could pre-calculate 2*Lat and 2*Lon for each point cutting out 2 more calculations for each comparison.

    None of this improves your algorithm per se but it should make it run faster and can be applied to any algorithm that needs to compare the distances between points.

提交回复
热议问题