It is necessary to calculate the angle of inclination of the segment, but taking into account the location of the beginning and end.

import math trox = float(3.0) troy = float(3.0) rxox = float(7.0) rxoy = float(5.0) len_line = math.sqrt(((rxox-trox)**2)+((rxoy-troy)**2)) print('%.3f' % len_line) angel = math.degrees(math.atan((rxoy-troy)/(rxox-trox))) print('%.3f' % angel) 

In the above code, the beginning of the segment is lower and to the left than the end. Because the angle is 26 degrees. It seems everything is clear. But if you swap the beginning and end of the segment, the angle value will be exactly the same. And I need to take into account the direction of the segment around its beginning. Theoretically, the angle should be 206 degrees. How to implement it?

  • That's right, the arctangent changes from -pi / 2 to pi / 2 - Kirill Malyshev
  • How to be that? - Rashid_s

2 answers 2

The fact is that the arctangent does not distinguish such cases. After all, tg(x) == tg(x + pi) . Therefore, the arctangent in both cases is the same, and in the range of -pi / 2 to pi / 2. Add math.pi to the corner if the segment starts to the right of its end.

 angel = math.atan((rxoy-troy)/(rxox-trox)) x1 = rxox # начало x2 = trox # конец if x1 > x2: angel += math.pi angel = math.degrees(angel) print('%.3f' % angel) 

PS You can add not math.pi to radians, but 180 to degrees.

To get the angle in the segment [0; 2 * pi], you can do so

for radians:

 angel %= 2*math.pi 

or for degrees:

 angel %= 360 
  • I also thought in this direction, but I think that in addition to the values ​​along the 0X axis, it is necessary to take into account the values ​​of 0U. - Rashid_s 2:29 pm
  • @ Rashid-s, no, it will always work. - Kirill Malyshev
  • try it yourself. trox = float (3.0) troy = float (3.0) rxox = float (7.0) rxoy = float (1.0) It turns out 153 degrees, but should in theory 334 - Rashid_s
  • @ Rashid-s, and what confuses you? The angle between the positive direction Ox and the vector is 153.435 degrees. It is not necessary to write float () everywhere. - Kirill Malyshev
  • @ Rashid-s, in my example, the vector starts at rxox, ends at trox. There is an angle of 153.435. If you look on the contrary, it turns out -26.565 If you need angle at [0; 2pi], do the following at the end: angel% = 360 - Kirill Malyshev
 angel = math.degrees(math.atan2(rxoy-troy)) 

I have already tried it. Does not fit. Still considers 26 degrees.

You want to say that two lines

 print math.degrees(math.atan2(1,1)) print math.degrees(math.atan2(-1,-1)) 

output two identical numbers?

  • I have already tried it. Does not fit. Still considers 26 degrees. - Rashid_s 2:12 pm