Difference Between Two Angles

// from http://codebase.dbp-site.com/code/find-difference-between-two-angles-25
function angleDifference(angle0:Number, angle1:Number):Number{
	return Math.abs((angle0 + 180 -  angle1) % 360 - 180);
}

trace("get the angle between:");
trace("350 and 10 =", angleDifference(350, 10));
trace("180 and -1 =", angleDifference(180, -1));
trace("-10 and 5 =", angleDifference(-10, 5));
trace("725 and -45 =", angleDifference(725, -45));
/* outputs:
get the angle between:
350 and 10 =  20
180 and -1 =  179
-10 and 5 =  15
725 and -45 =  50
*/

This snippet shows an easy way to find the difference between two angles. The tricky part about doing this is finding the difference between something like 350 and 1 (which should be 11).

Over the years I have done this a few different ways – I needed it for something today and realized that my way was a tad clunky (had a little redundant logic) – So with a quick google search I found a more elegant solution.

9 comments

  1. This is the best solution I have found. The next best is:

    abs = abs(angle0 – angle1);
    return min((2 * PI) – abs, abs);

    In PHP, it is about 2.5 slower compared to yours.

    NOTE: the solution I posted uses radians from pi to -pi.

  2. I don’t think your solution works for all inputs. If I put in 57 and 328 (so it is 57 – 328) I get 271 where the answer should be 89.

  3. Thank you for this post, works nice for the most values.

    I found the same error like Robert.

    I fixed it with an if clause:
    public static double angleDifference(double firstAngle, double secondAngle) {
    if (firstAngle < secondAngle) { double tmpAngle = firstAngle; firstAngle = secondAngle; secondAngle = tmpAngle; } return Math.abs((firstAngle + 180 - secondAngle) % 360 - 180); }

  4. WARNING!!!

    This solution and the alternate found in the comments are both incorrect. They can be used to find the angle difference assuming only one direction of rotation. Which is usually not what people mean when they say difference between angles.

    Unfortunately this page is currently the first result on google for the search term “Difference between angles”. A correct solution is

    double difference = secondAngle – firstAngle;
    while (difference 180) difference -= 360;
    return difference

    see the following link for an explanation.

    http://www.codeproject.com/Articles/59789/Calculate-the-real-difference-between-two-angles-k.aspx

  5. Hey Xavier… at some point a few months ago I realized this post was wrong. I’ve meaning to update it for ages but haven’t gotten around to it. I’ll update the post later today with your link and information. Thanks for pointing this out.

Leave a Reply

Your email address will not be published. Required fields are marked *