Thursday, August 22, 2013

Math: Directional statistics, calculating average of angles in Python

How does one calculate the average of a distribution of angles? The mean of 360 deg and 0 deg is not 180 degrees.
I was quite certain that while it is possible to get around the problem programatically, there should be a host of mathematical methods to deal with functions that have circular domains. That's directional statistics and it deals with statistics in certain non-Euclidean spaces.
In a nutshell, that's how I calculated the average of angles in Python (and in radians!):

def getCircularMean(angles):
  n = len(angles)
  sineMean = np.divide(np.sum(np.sin(angles)), n)
  cosineMean = np.divide(np.sum(np.cos(angles)), n)
  vectorMean = math.atan2(sineMean, cosineMean)
  return vectorMean


No comments:

Post a Comment