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.

=================

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

1

@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

1

For the absolute difference: Abs @ Mod[a – b, 2 Pi, -Pi].

– Michael E2

Jul 5 ’14 at 23:27

=================

2 Answers

2

=================

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[

MapThread[eldoDiff[##], mgDiff[##] &, Transpose[data]],

TableHeadings -> {None, {“eldo”, “mg”}}]

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

1

@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} *)