Sean Powell
Sean Powell

Reputation: 561

Angle between two lines is not always working

I am calcualting the angle between two lines on the following image enter image description here

with this code

# the lines are in the format (x1, y1, x2, y2)
def getAngle(line_1, line_2):
    angle1 = math.atan2(line_1[1] - line_1[3], line_1[0] - line_1[2])
    angle2 = math.atan2(line_2[1] - line_2[3], line_2[0] - line_2[2])

    result = math.degrees(abs(angle1 - angle2))
    if result < 0:
        result += 360

    return result

Now the function works between the two red lines (almost on top of each other) and the red and the green line. However, between the red and the blue line the fuction returns 239.1083 when it should be ~300. Since it is working in some of the cases and not others i am not sure what the problem is.

Some example inputs and outputs:

getAngle((316,309,316,-91), (316,309,421,209)) = 46.3971 # working
getAngle((316,309,316,-91), (199,239,316,309)) = 239.108 # should be around 300

Upvotes: 0

Views: 339

Answers (1)

LazyCoder
LazyCoder

Reputation: 1265

For the example getAngle((316,309,316,-91), (199,239,316,309)), The culprit is measurement of angles in this case.

Angles are getting calculated w.r.t. positive X axis. The angle which you have defined here, calculates phi in the given image below rather than theta, which you should be expecting. Since the rotation is negative in nature (observe the arrow for phi), any subsequent calculation must ensure positive rotation, rather than the negative one. Otherwise, you'll be short by the complementary angle, roughly.

In the given example, the correct angle of line2 should be about +210 degrees, or about -150 degrees. Similarly, the angle of line1 could be +90 or -90 degrees. Now, it's all in the game of which ones to add or subtract and how?

  • The 239.something, let's call it 240 is gotten by abs(90-(-150)) The

  • 300 you are expecting is gotten by abs(-90 - (+210)).

The difference of 60 degrees is the complement of theta = 30 degrees.

So, it's not so much as bad formula, it's bad argument passing and checking to get positive or negative angles.

Image2 Image1

Upvotes: 2

Related Questions