king rogers
king rogers

Reputation: 33

code to calculate the value of an angle

I have code where you give the 2 points a(x1,y1) and b(x2,y2) so that it calculates the angle between (alpha) them as shown in the image below:

enter image description here

I tried using this: angle = math.degrees(math.atan2((x1 - x2),(y1 - y2))) to calculate the angle but it wont give the corrct value when the angle coordinates are like this in the image below:

enter image description here

I need a function that can always get the accurate value of the angle when given the coordinates

y2 can be greater than or less than y1 but x2 should always be greater than x1

Upvotes: 1

Views: 1428

Answers (2)

Rory Daulton
Rory Daulton

Reputation: 22544

There are three difficulties in your problem. In most similar problems, the angle of the ray from (x1, y1) to (x2, y2) is wanted, but your problem is the other direction. Another difficulty is that you want the angle that goes clockwise from the negative y-axis, but standard trigonometry uses the angle that goes counterclockwise from the positive x-axis. The third difficulty is that the atan2 function sometimes returns negative angle values, but you want only positive values.

Here is the shortest one-line solution to your problem:

degrees(atan2(x2 - x1, y2 - y1))

This works by swapping the y's and the x's from the way they are normally used in the atan2 function, and by taking the negatives of the parameters. This flips the points (and the entire plane) to a position where the atan2 function works as usual. Note that if x1 > x2 the result will be negative.

Here is some test code:

print('Straight down zero:', anglealpha(0, -1, 0, 0))
print('Straight up 180:   ', anglealpha(0, 1, 0, 0))
print('Straight left 90:  ', anglealpha(-1, 0, 0, 0))
print('Down left 45:      ', anglealpha(-1, -1, 0, 0))
print('Up left 135:       ', anglealpha(-1, 1, 0, 0))

giving the results:

Straight down zero: 0.0
Straight up 180:    180.0
Straight left 90:   90.0
Down left 45:       45.0
Up left 135:        135.0

Upvotes: 3

user5012940
user5012940

Reputation:

it seems you are trying to find angle between two lines. Line 1 is between (X1, Y1) and (X2, Y2) and Line 2 is between (X2, Y2) and (X2, 0) -since its a vertical. Angle is the difference between two slopes. Slope of line 1: (y2 - y1)/(x2 - x1)

You wont be able to do this for line 2. Using triangle rules, instead of finding the angle at vertical, you can find the angle the line makes at X1, Y1 will the horizontal X line subtract it from 90. Subtract this from 90.

For your second angle, it is same but you don't need to subtract from 90. I'm sure you can convert it into Python code

Upvotes: 0

Related Questions