0
$\begingroup$

Given two arbitrary lines using primitives such as Line[{p1, p2}] in the plane, how can the acute angle between them be computed?

line1 = Line[{{x1, y1}, {x2, y2}}];
line2 = Line[{{x3, y3}, {x4, y4}}];

This seems like such a fundamental operation, surely there is a simple way to do this in Mathematica?

$\endgroup$
2
  • 1
    $\begingroup$ Take the difference of the endpoints of the two line segments, and then use VectorAngle[]. $\endgroup$ Commented Feb 15, 2023 at 18:36
  • $\begingroup$ Regarding your deleted answer: don't use Abs[]; just the plain differences should work. $\endgroup$ Commented Feb 15, 2023 at 18:49

2 Answers 2

4
$\begingroup$

I will load a demo using PlanarAngle.

Clear[line1, line2, sol]
line1 = InfiniteLine@RandomReal[{0, 1}, {2, 2}];
line2 = InfiniteLine@RandomReal[{0, 1}, {2, 2}];
(*RegionQ/@{line1,line2};*)
sol = RegionIntersection[line1, line2][[-1]];
ang = Min[#, 
     180 - #] &@(PlanarAngle[{line1[[-1, -1]], sol, 
       line2[[-1, -1]]}] 180/π);
Graphics[{
  Red, Dashed, line1
  , Blue, Dashed, line2
  , AbsolutePointSize[6], Point@(line1[[-1]])
  , AbsolutePointSize[6], Point@(line2[[-1]])
  , Thick, Dashing[{}], Red, line1 /. InfiniteLine :> Line
  , Thick, Dashing[{}], Blue, line2 /. InfiniteLine :> Line
  , Black, Point@sol, Darker@Green, Thin, Circle[sol, 0.04]
  }
 , Frame -> True
 (*,AxesOrigin\[Rule]sol[[-1]]*)
 , PlotRange -> Transpose@{sol + 1, sol - 1}
 , PlotRangeClipping -> True
 , PlotLabel -> Text[Style[ToString@ang <> "°", 16]]
 ]

A sample output is attached:

enter image description here

$\endgroup$
2
$\begingroup$

From J.M.'s comment:

lineLineAngle[Line[{X1_, X2_}], Line[{X3_, X4_}]] := VectorAngle[X1 - X2, X4 - X3]

example:

line1 = Line@RandomReal[{0, 1}, {2, 2}];
line2 = Line@RandomReal[{0, 1}, {2, 2}];

lineLineAngle[line1, line2]

enter image description here

$\endgroup$
2
  • 1
    $\begingroup$ You should accept your own answer as this is the correct way of doing this calculation. I was demonstrating the use of PlanarAngle. It can be used to calculate interior angles when polygon points are known, for instance. $\endgroup$
    – Syed
    Commented Feb 16, 2023 at 12:58
  • $\begingroup$ @Syed, thanks I will $\endgroup$ Commented Feb 16, 2023 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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