I'm trying to reduce a set of lat/lons (each with it's own weight) into one lat/lon that is the center of mass of all of the points.
however when I map the results the average point falls no where near where I think it should be (I've tested on multiple sets of points).
here's my code, in python, based on these two answers:
How to find a point half way between two other points?
Computing an averaged latitude and longitude coordinates
import math
import nummpy
import math
def toCartesian(t):
latD,longD = t
latR = math.radians(latD)
longR = math.radians(longD)
return (
math.cos(latR)*math.cos(longR),
math.cos(latR)*math.sin(longR),
math.sin(latR)
)
def toSpherical(t):
x,y,z = t
r = math.hypot(x,y)
if r == 0:
if z > 0:
return (90,0)
elif z< 0:
return (-90,0)
else:
return None
else:
return (math.degrees(math.atan2(z, r)), math.degrees(math.atan2(y,x)))
xyz = numpy.asarray([0.0,0.0,0.0])
total = 0
for p in points:
weight = p["weight"]
total += weight
xyz += numpy.asarray(toCartesian((p["lat"],p["long"])))*weight
avgXYZ = xyz/total
avgLat, avgLong = toSpherical(avgXYZ)
print avgLat,avgLong
atan2(r,z)ought to beatan2(z,r). With numerical code like this, it's important to write little testing modules for your functions (liketoSphericalandtoCartesian) and exercise them well so that you know you can trust them. Why don't you do that and see whether your problems go away? – whuber Jun 14 '13 at 14:35