Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which side of a line a point lies [duplicate]

I have a set of points. I want to separate them into 2 distinct sets. To do this, I choose two points (a and b) and draw an imaginary line between them. Now I want to have all points that are left from this line in one set and those that are right from this line in the other set.

How can I tell for any given point z whether it is in the left or in the right set? I tried to calculate the angle between a-z-b – angles smaller than 180 are on the right hand side, greater than 180 on the left hand side – but because of the definition of ArcCos, the calculated angles are always smaller than 180°. Is there a formula to calculate angles greater than 180° (or any other formula to chose right or left side)?

like image 951
Aaginor Avatar asked Oct 13 '09 14:10

Aaginor


People also ask

How do you determine if two points lie on the same side of a line?

You should be able to plug in the x and y values for both points, and if both make the equation y < mx + b or both make it y > mx + b, they are on the same side. If either point satisfies the equation (y = mx + b), that point is on the line.

How do you check if a point is above or below a line?

If the line equation is y=ax+b and the coordinates of a point is (x0,y0) then compare y0 and ax0+b, for example if y0>ax0+b then the point is above the line, etc.


2 Answers

Try this code which makes use of a cross product:

public bool isLeft(Point a, Point b, Point c){      return ((b.X - a.X)*(c.Y - a.Y) - (b.Y - a.Y)*(c.X - a.X)) > 0; } 

Where a = line point 1; b = line point 2; c = point to check against.

If the formula is equal to 0, the points are colinear.

If the line is horizontal, then this returns true if the point is above the line.

like image 88
jethro Avatar answered Sep 20 '22 09:09

jethro


Use the sign of the determinant of vectors (AB,AM), where M(X,Y) is the query point:

position = sign((Bx - Ax) * (Y - Ay) - (By - Ay) * (X - Ax)) 

It is 0 on the line, and +1 on one side, -1 on the other side.

like image 22
Eric Bainville Avatar answered Sep 23 '22 09:09

Eric Bainville