Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
2  
angleDifference[a_, b_] := With[{d = Mod[a - b, 2 π]}, If[d > π, d - 2 π, d]] –  Rahul Narain Jul 5 at 19:24
    
Thank you. This answers the question. –  user16104 Jul 5 at 19:32
1  
@RahulNarain Or angleDifference[a_, b_] := -Mod[b - a, 2 Pi, -Pi] –  Michael E2 Jul 5 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 at 23:26
1  
For the absolute difference: Abs @ Mod[a - b, 2 Pi, -Pi]. –  Michael E2 Jul 5 at 23:27

2 Answers 2

up vote 3 down vote accepted

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"}}]

table

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

share|improve this answer
    
+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 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 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}  *)
share|improve this answer

Your Answer

 
discard

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.