tags:

views:

781

answers:

2

Hi folks,

I have a set of points. I want to separate them into 2 distinct sets. To do this, I chose 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.

My question is: How can I tell for any given point z wheter 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 angels are always smaller than 180°. Is there a formula to calculate angels greater than 180° (or any other formula to chose right or left side)?

Thanks in advance, Frank

+11  A: 

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.

Eric Bainville
+1 nice, with one thing to be aware of: rounding error can be a concern when the point is very nearly on the line. Not a problem for *most* uses, but it does bite people from time to time.
Stephen Canon
Great! This is a nice one, without sinus, arccos and such :)Rounding errors are not a problem here, as I use the separating in an algorithm to calculate the convex hull of the pointset and draw a polyline around them. If a point is just outside the hull, it is no big problem.
Aaginor
Should you find yourself in a situation where rounding error on this test is causing you problems, you will want to look up Jon Shewchuk's "Fast Robust Predicates for Computational Geometry".
Stephen Canon
For clarification, this is the same as the Z-component of the cross product between the the line (b-a) and the vector to the point from a (m-a). In your favorite vector-class:position = sign((b-a).cross(m-a)[2])
larsm
+2  A: 

Using the equation of the line ab, get the x-coordinate on the line at the same y-coordinate as the point to be sorted.

  • If point's x > line's x, the point is to the right of the line.
  • If point's x < line's x, the point is to the left of the line.
  • If point's x == line's x, the point is on the line.
mbeckish