# How to get the absolute difference between two angles

I need a function that will give me the shortest separation between angles that range from -pi to pi. For example if I have two angles 3pi/4 and -3pi/4, I would like a function that will tell me pi/2 instead of 3pi/2.

-
angleDifference[a_, b_] := With[{d = Mod[a - b, 2 π]}, If[d > π, d - 2 π, d]] – Rahul Jul 5 '14 at 19:24
Thank you. This answers the question. – user16104 Jul 5 '14 at 19:32
@RahulNarain Or angleDifference[a_, b_] := -Mod[b - a, 2 Pi, -Pi] – Michael E2 Jul 5 '14 at 23:14
The title says absolute difference, but the question specifies the range to be -π το π, which suggests negative answers are possible. Do you want the (signed) difference or the absolute value of the difference? – Michael E2 Jul 5 '14 at 23:26
For the absolute difference: Abs @ Mod[a - b, 2 Pi, -Pi]. – Michael E2 Jul 5 '14 at 23:27

Eldo's answer only works for a very restricted set of inputs. Here is a much more general solution.

validNum = Except[_Complex, _?NumericQ];

eldoDiff[θ1 : validNum, θ2 : validNum] :=
Plus @@ ({θ1, θ2} /. Rational[a_, b_] :> Rational[1, b])

mgDiff[θ1 : validNum, θ2 : validNum] :=
(With[{a = Mod[Abs[θ1 - θ2], 2 π]}, Min[a, 2 π - a]] /. Degree -> π/180)

data = {{-((3 π)/4), (3 π)/4}, {-135 °, 135 °}, {-2, 1}};
TableForm[


eldoDiff gives the correct result only for the first pair of arguments, while mgDiff gives the correct result for all three pairs.

-
+1, BUT ! to account for all cases somebody should edit the question ("shortest separation between angles that range from -pi to pi"). – eldo Jul 6 '14 at 0:19
@edo. You're right in thinking the question could have been posed better. However, I think it is best to try read between the lines and come up with an answer that will be useful in the broadest possible circumstances. Going beyond the strict requirements of the original question is usually a good idea. Remember, as well as trying to help the OP, we should also support the SE goal of building an archival body of useful Mathematica practice in QA form. – m_goldberg Jul 6 '14 at 3:27
VectorAngle[{Cos[#1], Sin[#1]}, {Cos[#2], Sin[#2]}] & @@ {3 Pi/4, -3 Pi/4}


Edit.

taking the point mentioned by m_goldberg:

data = {{-((3 π)/4), (3 π)/4}, {-135 °, 135 °}, {-2, 1}};

VectorAngle[{Cos[#1], Sin[#1]}, {Cos[#2], Sin[#2]}] & @@@ data//Simplify

(*  {Pi/2, Pi/2, 3}  *)

-