# Most efficient way to calculate angle between two line-segments that do not necessarily touch each other

Although I found answers on calculating angles from vectors, I didn't find a specific way to calculate angles between line-segments that do not necessarily touch each other (I say "not necessarily because I will apply to different cases).

See the figure below:

Consider that I know the 2D position of all 4 red points. I am using C# here. What would be the cheapest way of calculating the angles formed by line-segments that do not touch each other, such like the ones above?

• Do you know how to calculate the angle between two lines that do touch each other? Why would this be any different? – congusbongus Oct 20 '15 at 5:54
• Isn't it the angle between the vectors you want here? Whether the segments touch or not you can consider the angle between two infinite rays which is simply the dot product of the two vectors – Steven Oct 20 '15 at 5:54
• @Steven so, if the points are named A, B, C and D, the angle would be equal Dot( A-B , C-D)? The subtraction is for getting the vectors from the points (should I take the absolute values to get rid of the sign?) – Louis15 Oct 20 '15 at 5:59
• @Steven I see what you mean. So the angle equals arccos[Dot( A-B , C-D)/abs(A-B)*abs(C-D)]. Is that right? Anyway, regarding computational complexity, I thought it would be possible to do avoid divisions or expensive trigonometry, but it's seems that it might be impossible. – Louis15 Oct 20 '15 at 6:20
• Not sure what you intend to have when you say don't touch each other. It may be not that easy, as the dot product considers the non-touch case.Here it might depend on your chosen circle radius and circle center. Consider the case where the segment <CD> is parallel to <AB> but still not touching each other as in your illustration; then we would have a degree less than 180 degree due to the gap between them. Also, if the circle is small enough, it will just go round to 180 degrees. Is that what you want to calculate or are you happy with the angle between vectors case? – Majte Oct 20 '15 at 9:21

Let s1 and s2 the segments, so you can calculate the angle of each using atan2(s.p1.y-s.p2.y,s.p1.x-s.p2.x) where p1 and p2 are the two points defining s;

double theta1 = Math.atan2(s1.p1.y-s1.p2.y,s1.p1.x-s1.p2.x);
double theta2 = Math.atan2(s2.p1.y-s2.p2.y,s2.p1.x-s2.p2.x);


Taking the absolute value of the difference, you get the angle between the segments:

double diff = Math.abs(theta1-theta2);


And finally, you can use the minor angle:

double angle=min(diff,Math.abs(180-diff));