Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm making a prototype for android that pulls compass data from the phone. I want to stabilize it so it is less jerky, by taking the average of the last couple of readings.

I have done this for accelerometer readings with great success, but adding every measurement to a queue and then collapsing it and dividing it by the queue size (= calculating the average) but for angles this is different.

If my measurements are for example:

350, 359, 360

I could calculate the average as 356.3

But if my measurements are

350 359, 1

Then my average is 236 which is a radically different angle.

Is there any way you guys can think of I could deal with this?

share|improve this question
up vote 5 down vote accepted

You could convert each angle to a 2D vector and sum the vectors, then convert the result back to an angle.

In pseudocode:

totalVector = [0, 0]
for each angle:
    vector = [cos(angle), sin(angle)]
    totalVector += vector
if length(totalVector) < aSmallNumber:
    # error, angles are all over the place so there's no meaningful average
avgAngle = atan2(totalVector.y, totalVector.x)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.